def register(self, model, trans_class): """ Registers the given model for use with c3po translation system. The model should be Model classes, not instances. If a model is already registered, this will raise AlreadyRegistered exception. """ assert hasattr(model, '_meta'), 'Model must derive from Model.' # check if model is already registered if model in self._registry: raise AlreadyRegistered( u'The model %s.%s is already registered! Registry dump: %s' % ( model.__module__, model.__name__, self.get_registered_models() ) ) # setup translations model opts = trans_class(model) trans_model = self._create_translation_model(model, opts) models.register_models(model._meta.app_label, trans_model) # Clear related object caches so that Django reprocesses objects. model._meta._fill_related_objects_cache() model._meta.init_name_map() # Configured and register the multilingual model and the # translation_class. model._translation_model = trans_model self._registry[model] = opts
def register(self, master_model, translation_class=None, **options): """ Sets everything up for the given master model using a set of registration options (ModelTranslation attributes). If a translation class isn't given, it will use ModelTranslation (the default translation options). If keyword arguments are given -- e.g., fields -- they'll overwrite the translation_class attributes. """ if master_model in self._registry: raise AlreadyRegistered('The model "%s" has is already registered for translation' % master_model.__name__) # If not translation_class given use default options. if not translation_class: translation_class = ModelTranslation # If we got **options then dynamically construct a subclass of translation_class with those **options. if options: translation_class = type('%sTranslation' % master_model.__name__, (translation_class,), options) # Validate the translation_class (just in debug mode). if settings.DEBUG: from model_i18n.validation import validate validate(translation_class, master_model) opts = translation_class(master_model) # Set up master_model as a multilingual model using translation_class options translation_model = self.create_translation_model(master_model, opts) models.register_models(master_model._meta.app_label, translation_model) self.setup_master_model(master_model, translation_model) # This probably will become a class method soon. setup_admin(master_model, translation_model) # Setup django-admin support # Register the multilingual model and the used translation_class. self._registry[master_model] = opts
def register(self, master_model, translation_class=None, **options): """ Sets everything up for the given master model using a set of registration options (ModelTranslation attributes). If a translation class isn't given, it will use ModelTranslation (the default translation options). If keyword arguments are given -- e.g., fields -- they'll overwrite the translation_class attributes. """ if master_model in self._registry: raise AlreadyRegistered( 'The model "%s" has is already registered for translation' % master_model.__name__) # If not translation_class given use default options. if not translation_class: translation_class = ModelTranslation # If we got **options then dynamically construct a subclass of translation_class with those **options. if options: translation_class = type('%sTranslation' % master_model.__name__, (translation_class, ), options) # Validate the translation_class (just in debug mode). if settings.DEBUG: from model_i18n.validation import validate validate(translation_class, master_model) opts = translation_class(master_model) # Set up master_model as a multilingual model using translation_class options translation_model = self.create_translation_model(master_model, opts) models.register_models(master_model._meta.app_label, translation_model) self.setup_master_model( master_model, translation_model ) # This probably will become a class method soon. setup_admin(master_model, translation_model) # Setup django-admin support # Register the multilingual model and the used translation_class. self._registry[master_model] = opts
def __init__(self, config=None): """ Makes sure the models required by the test are registed within the Django eco-system. They only need to be required if they would otherwise go uninstalled. """ self.config = config if config else {} for model in self.requires_models: # Register with Django's model system. models.register_models('contextual', model) try: # Register the models with Django's admin system. # Testing raises AlreadyRegistered as I guess the # class is instantiated twice. Let me know a better way. admin.site.register(model) except admin.sites.AlreadyRegistered: pass # Now we test the passed in config dictionary had all # the necessary for configuration keys. for key, reason in self.requires_config_keys.iteritems(): if not key in self.config: raise ImproperlyConfigured, \ "%s requires the key \"%s\" in its config dictionary: %s" % \ (self.__class__.__name__, key, reason)
from photologue.models import PhotoSize from secretballot.models import Vote from jmbo.admin import ModelBaseAdmin from jmbo.models import ModelBase from jmbo.utils.tests import RequestFactory from jmbo.management.commands import jmbo_publish from jmbo import USE_GIS if USE_GIS: from atlas.models import Location, City, Country class DummyRelationalModel1(models.Model): pass models.register_models('jmbo', DummyRelationalModel1) class DummyRelationalModel2(models.Model): pass models.register_models('jmbo', DummyRelationalModel2) class DummyTargetModelBase(ModelBase): pass models.register_models('jmbo', DummyTargetModelBase) class DummySourceModelBase(ModelBase): points_to = models.ForeignKey('DummyModel') points_to_many = models.ManyToManyField('DummyModel', related_name='to_many')
import unittest from django.db import models from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TestModel(models.Model): pass models.register_models('databaserouters', TestModel) class AppModelRouterTestCase(unittest.TestCase): def setUp(self): from databaserouters import AppModelRouter settings.APP_MODEL_DATABASE_ROUTING = {} self.router = AppModelRouter() def test_check_configuration(self): # If no APP_MODEL_DATABASE_ROUTING settings is specified an ImproperlyConfigured # exception should be raised. try: del settings.APP_MODEL_DATABASE_ROUTING except AttributeError: pass self.assertRaises(ImproperlyConfigured, self.router.check_configuration) # If an invalid APP_MODEL_DATABASE_ROUTING setting is specified an ImproperlConfigured # exception should be raised. settings.APP_MODEL_DATABASE_ROUTING = None self.assertRaises(ImproperlyConfigured, self.router.check_configuration)
from django.contrib.auth.models import User from django import forms from django.test import TestCase from django.conf import settings from django.test.client import Client as BaseClient, FakePayload, \ RequestFactory from django.core.handlers.wsgi import WSGIRequest from django.core.urlresolvers import reverse from simple_autocomplete.widgets import AutoCompleteWidget from simple_autocomplete.monkey import _simple_autocomplete_queryset_cache class DummyModel(models.Model): user = models.ForeignKey(User, null=True, blank=True) models.register_models('simple_autocomplete', DummyModel) class EditDummyForm(forms.ModelForm): class Meta: model = DummyModel class Client(BaseClient): """Bug in django/test/client.py omits wsgi.input""" def _base_environ(self, **request): result = super(Client, self)._base_environ(**request) result['HTTP_USER_AGENT'] = 'Django Unittest' result['HTTP_REFERER'] = 'dummy' result['wsgi.input'] = FakePayload('')
from jmbo.admin import ModelBaseAdmin from jmbo.models import ModelBase from jmbo.utils.tests import RequestFactory from jmbo.management.commands import jmbo_publish from photologue.models import PhotoSize from secretballot.models import Vote from atlas.models import Location, City, Country class DummyRelationalModel1(models.Model): pass models.register_models('jmbo', DummyRelationalModel1) class DummyRelationalModel2(models.Model): pass models.register_models('jmbo', DummyRelationalModel2) class DummyModel(ModelBase): test_editable_field = models.CharField(max_length=32) test_non_editable_field = models.CharField(max_length=32, editable=False) test_foreign_field = models.ForeignKey('DummyRelationalModel1', blank=True, null=True)
from jmbo.admin import ModelBaseAdmin from jmbo.models import ModelBase from jmbo.utils.tests import RequestFactory from jmbo.management.commands import jmbo_publish from jmbo import USE_GIS if USE_GIS: from atlas.models import Location, City, Country class DummyRelationalModel1(models.Model): pass models.register_models('jmbo', DummyRelationalModel1) class DummyRelationalModel2(models.Model): pass models.register_models('jmbo', DummyRelationalModel2) class DummyTargetModelBase(ModelBase): pass models.register_models('jmbo', DummyTargetModelBase)
from django.template import Template from django.template.defaultfilters import slugify from django.test import TestCase from django.test.client import Client from jmbo.admin import ModelBaseAdmin from jmbo.models import ModelBase from jmbo.utils.tests import RequestFactory from photologue.models import PhotoSize from secretballot.models import Vote class DummyRelationalModel1(models.Model): pass models.register_models('jmbo', DummyRelationalModel1) class DummyRelationalModel2(models.Model): pass models.register_models('jmbo', DummyRelationalModel2) class DummyModel(ModelBase): test_editable_field = models.CharField(max_length=32) test_non_editable_field = models.CharField(max_length=32, editable=False) test_foreign_field = models.ForeignKey( 'DummyRelationalModel1', blank=True, null=True )
from django.test import TestCase from django.conf import settings from django.test.client import Client as BaseClient, FakePayload, \ RequestFactory from django.core.handlers.wsgi import WSGIRequest from django.core.urlresolvers import reverse from simple_autocomplete.widgets import AutoCompleteWidget from simple_autocomplete.monkey import _simple_autocomplete_queryset_cache class DummyModel(models.Model): user = models.ForeignKey(User, null=True, blank=True) models.register_models('simple_autocomplete', DummyModel) class EditDummyForm(forms.ModelForm): class Meta: model = DummyModel class Client(BaseClient): """Bug in django/test/client.py omits wsgi.input""" def _base_environ(self, **request): result = super(Client, self)._base_environ(**request) result['HTTP_USER_AGENT'] = 'Django Unittest' result['HTTP_REFERER'] = 'dummy' result['wsgi.input'] = FakePayload('') return result
opts=_create_field_opts(ftype, **kwargs)) def _generate_fields(fields): return '\n'.join([_build_field_factory(**v) for v in fields]) def _models_from_dict(data): for k, v in data.items(): name = k.capitalize() fields = v.get('fields', []) source = _MODEL_TMPL.format( name=name, title=v.get('title', name), fields=_generate_fields(fields)) yield (name, source, [{'type': 'auto', 'id': 'id', 'title': 'Id'}] + fields) # Entry point MODELS = {} with open('tables', 'r') as f: __all__ = ['MODELS'] for name, source, fields_spec in _models_from_dict(yaml.load(f)): exec (source) __all__.append(name) MODELS[name] = {'instance': locals()[name], 'fields': fields_spec} models.register_models('automod', *[m['instance'] for m in MODELS.values()])
import unittest from django.contrib import admin from django.contrib.auth.models import Group, User from django.contrib.contenttypes.models import ContentType from django.db import models from sharing import utils from sharing.admin import ShareAdminMixin from sharing.models import GroupShare, UserShare from snippetscream import RequestFactory class TestModel(models.Model): pass models.register_models('sharing', TestModel) class TestModelAdmin(ShareAdminMixin, admin.ModelAdmin): pass admin.site.register(TestModel, TestModelAdmin) class ShareBackendTestCase(unittest.TestCase): def setUp(self): # Create test object, users and groups. self.obj = TestModel.objects.create(id=1) self.user = User.objects.create(username='******') self.group = Group.objects.create(name='group') self.group_user = User.objects.create(username='******') self.group_user.groups.add(self.group) self.group_user.save() def tearDown(self):
from datetime import datetime, timedelta import unittest from django.conf import settings from django.contrib.sites.models import Site from django.db import models as django_models from cal import models from cal.models import Calendar, Entry, EntryItem from panya.models import ModelBase class WantedContent(ModelBase): pass django_models.register_models('cal', WantedContent) class UnwantedContent(ModelBase): pass django_models.register_models('cal', UnwantedContent) class EntrySaveHandlersTestCase(unittest.TestCase): def setUp(self): content = ModelBase() content.save() self.content = content calendar = models.Calendar() calendar.save() self.calendar = calendar def test_save_handler_does_not_repeat(self): # create an entry