Example #1
0
def register_to_payment(order_class, **kwargs):
    """
    A function for registering unaware order class to ``getpaid``. This will
    generate a ``Payment`` model class that will store payments with
    ForeignKey to original order class

    This also will build a model class for every enabled backend.
    """
    global Payment
    global Order
    class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
        objects = PaymentManager()
        class Meta:
            ordering = ('-created_on',)
            verbose_name = _("Payment")
            verbose_name_plural = _("Payments")

    Order = order_class

    # Now build models for backends

    backend_models_modules = import_backend_modules('models')
    for backend_name, models in backend_models_modules.items():
        app_cache.register_models(backend_name, *models.build_models(Payment))
    return Payment
Example #2
0
    def test_files_content(self):
        self.assertTableNotExists("migrations_unicodemodel")
        cache.register_models('migrations', UnicodeModel)
        call_command("makemigrations", "migrations", verbosity=0)

        init_file = os.path.join(self.migration_dir, "__init__.py")

        # Check for existing __init__.py file in migrations folder
        self.assertTrue(os.path.exists(init_file))

        with open(init_file, 'r') as fp:
            content = force_text(fp.read())
            self.assertEqual(content, '')

        initial_file = os.path.join(self.migration_dir, "0001_initial.py")

        # Check for existing 0001_initial.py file in migration folder
        self.assertTrue(os.path.exists(initial_file))

        with open(initial_file, 'r') as fp:
            content = force_text(fp.read())
            self.assertTrue('# encoding: utf8' in content)
            self.assertTrue('migrations.CreateModel' in content)

            if six.PY3:
                self.assertTrue('úñí©óðé µóðéø' in content)  # Meta.verbose_name
                self.assertTrue('úñí©óðé µóðéøß' in content)  # Meta.verbose_name_plural
                self.assertTrue('ÚÑÍ¢ÓÐÉ' in content)  # title.verbose_name
                self.assertTrue('“Ðjáñgó”' in content)  # title.default
            else:
                self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8' in content)  # Meta.verbose_name
                self.assertTrue('\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf' in content)  # Meta.verbose_name_plural
                self.assertTrue('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9' in content)  # title.verbose_name
                self.assertTrue('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d' in content)  # title.default
Example #3
0
def register_to_payment(order_class, **kwargs):
    """
    A function for registering unaware order class to ``getpaid``. This will
    generate a ``Payment`` model class that will store payments with
    ForeignKey to original order class

    This also will build a model class for every enabled backend.
    """
    global Payment
    global Order

    class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
        objects = PaymentManager()

        class Meta:
            ordering = ('-created_on', )
            verbose_name = _("Payment")
            verbose_name_plural = _("Payments")

    Order = order_class

    # Now build models for backends

    backend_models_modules = import_backend_modules('models')
    for backend_name, models in backend_models_modules.items():
        app_cache.register_models(backend_name, *models.build_models(Payment))
    return Payment
Example #4
0
    def test_failing_migration(self):
        #21280 - If a migration fails to serialize, it shouldn't generate an empty file.
        cache.register_models('migrations', UnserializableModel)

        with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'):
            with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}):
                    call_command("makemigrations", "migrations", verbosity=0)

        initial_file = os.path.join(self.migration_dir, "0001_initial.py")
        self.assertFalse(os.path.exists(initial_file))
Example #5
0
def build_payment_model(order_class, **kwargs):
	global Payment
	global Order
	class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
		pass
	Order = order_class
	bknd_models_modules = import_backend_modules('models')
	for bknd_name, models in bknd_models_modules.items():
		app_cache.register_models(bknd_name, *models.build_models(Payment))
	return Payment
Example #6
0
    def test_failing_migration(self):
        #21280 - If a migration fails to serialize, it shouldn't generate an empty file.
        cache.register_models('migrations', UnserializableModel)

        with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'):
            with override_settings(
                    MIGRATION_MODULES={"migrations": self.migration_pkg}):
                call_command("makemigrations", "migrations", verbosity=0)

        initial_file = os.path.join(self.migration_dir, "0001_initial.py")
        self.assertFalse(os.path.exists(initial_file))
Example #7
0
def build_payment_model(order_class, **kwargs):
    global Payment
    global Order

    class Payment(PaymentFactory.construct(order=order_class, **kwargs)):
        pass

    Order = order_class
    bknd_models_modules = import_backend_modules('models')
    for bknd_name, models in bknd_models_modules.items():
        app_cache.register_models(bknd_name, *models.build_models(Payment))
    return Payment
Example #8
0
    def setUpClass(cls):
        # Modify sys path
        cls.old_sys_path = sys.path[:]
        sys.path.append(os.path.dirname(os.path.abspath(__file__)))

        # Install test app, we need to use it for syncdb, so we can not use `override_settings`
        cls.old_installed_apps = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['ml_test_app']
        # Install `ml_test_app`
        map(load_app, settings.INSTALLED_APPS)
        cache.register_models('ml_test_app', Multiling, Multiling._meta.translation_model)
        call_command('syncdb', verbosity=0)
Example #9
0
    def test_files_content(self):
        self.assertTableNotExists("migrations_unicodemodel")
        cache.register_models('migrations', UnicodeModel)
        with override_settings(
                MIGRATION_MODULES={"migrations": self.migration_pkg}):
            call_command("makemigrations", "migrations", verbosity=0)

        init_file = os.path.join(self.migration_dir, "__init__.py")

        # Check for existing __init__.py file in migrations folder
        self.assertTrue(os.path.exists(init_file))

        with open(init_file, 'r') as fp:
            content = force_text(fp.read())
            self.assertEqual(content, '')

        initial_file = os.path.join(self.migration_dir, "0001_initial.py")

        # Check for existing 0001_initial.py file in migration folder
        self.assertTrue(os.path.exists(initial_file))

        with codecs.open(initial_file, 'r', encoding='utf-8') as fp:
            content = fp.read()
            self.assertTrue('# encoding: utf8' in content)
            self.assertTrue('migrations.CreateModel' in content)

            if six.PY3:
                self.assertTrue('úñí©óðé µóðéø'
                                in content)  # Meta.verbose_name
                self.assertTrue('úñí©óðé µóðéøß'
                                in content)  # Meta.verbose_name_plural
                self.assertTrue('ÚÑÍ¢ÓÐÉ' in content)  # title.verbose_name
                self.assertTrue('“Ðjáñgó”' in content)  # title.default
            else:
                self.assertTrue(
                    '\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8'
                    in content)  # Meta.verbose_name
                self.assertTrue(
                    '\\xfa\\xf1\\xed\\xa9\\xf3\\xf0\\xe9 \\xb5\\xf3\\xf0\\xe9\\xf8\\xdf'
                    in content)  # Meta.verbose_name_plural
                self.assertTrue('\\xda\\xd1\\xcd\\xa2\\xd3\\xd0\\xc9'
                                in content)  # title.verbose_name
                self.assertTrue('\\u201c\\xd0j\\xe1\\xf1g\\xf3\\u201d'
                                in content)  # title.default
Example #10
0
def create_through(field, model, to):
    """
    Create a dummy 'through' model for MongoDBManyToMany relations. Django assumes there is a real
    database model providing the relationship, so we simulate it. This model has to have
    a ForeignKey relationship to both models. We will also override the save() and delete()
    methods to pass the adding and removing of related objects to the relation manager.
    """
    obj_name = model._meta.object_name + to._meta.object_name + 'Relationship'
    to_module_name = to._meta.module_name
    model_module_name = model._meta.module_name

    class ThroughQuerySet(object):
        def __init__(self, relationship_model, *args, **kwargs):
            self.to = to
            self.model = relationship_model
            self.model_instance = None
            self.related_manager = None
            self.to_instance = None
            self.db = 'default'

        def filter(self, *args, **kwargs):
            if model_module_name in kwargs:
                # Relation, set up for querying by the model
                self.model_instance = kwargs[model_module_name]
                self.related_manager = getattr(self.model_instance, field.name)
                # Now we know enough to retrieve the actual query set
                queryset = self.related_manager.all(
                    appear_as_relationship=(self.model, self.model_instance,
                                            None, model_module_name,
                                            to_module_name)).using(self.db)
                return queryset
            if to_module_name in kwargs:
                # Reverse relation, set up for querying by the to model
                self.to_instance = kwargs[to_module_name]
                self.reverse_manager = getattr(self.to_instance,
                                               field.rel.related_name)
                queryset = self.reverse_manager._relationship_query_set(
                    self.model, self.to_instance, model_module_name,
                    to_module_name).using(self.db)
                return queryset
            return self

        def exists(self, *args, **kwargs):
            return False

        def ordered(self, *args, **kwargs):
            return self

        def using(self, db, *args, **kwargs):
            self.db = db
            return self

        def get(self, *args, **kwargs):
            # Check if it's a magic key
            if 'pk' in kwargs and isinstance(
                    kwargs['pk'], basestring) and '$' in kwargs['pk']:
                model_id, direction, to_id = kwargs['pk'].split('$', 2)
                if direction == 'r':
                    # It's a reverse magic key
                    to_id, model_id = model_id, to_id
                if direction == 'r':
                    # Query in reverse
                    self.to_instance = self.to.objects.get(pk=to_id)
                    self.reverse_manager = getattr(self.to_instance,
                                                   field.rel.related_name)
                    queryset = self.reverse_manager._relationship_query_set(
                        self.model, self.to_instance, model_module_name,
                        to_module_name).using(self.db)
                    obj = queryset.get(pk=model_id)
                    return obj
                else:
                    self.model_instance = model.objects.get(pk=model_id)
                    self.related_manager = getattr(self.model_instance,
                                                   field.name)
                    queryset = self.related_manager.all(
                        appear_as_relationship=(self.model,
                                                self.model_instance, None,
                                                model_module_name,
                                                to_module_name)).using(self.db)
                    return queryset.get(pk=to_id)
            # Normal key
            return None

        def __len__(self):
            # Won't work, must be accessed through filter()
            raise Exception('ThroughQuerySet relation unknown (__len__)')

        def __getitem__(self, key):
            # Won't work, must be accessed through filter()
            raise Exception('ThroughQuerySet relation unknown (__getitem__)')

    class ThroughManager(MongoDBManager):
        def get_query_set(self):
            return ThroughQuerySet(self.model)

    class Through(models.Model):
        class Meta:
            auto_created = model

        objects = ThroughManager()
        locals()[to_module_name] = models.ForeignKey(to, null=True, blank=True)
        locals()[model_module_name] = models.ForeignKey(model,
                                                        null=True,
                                                        blank=True)

        def __unicode__(self):
            return unicode(getattr(self,
                                   model_module_name)) + u' : ' + unicode(
                                       getattr(self, to_module_name))

        def save(self, *args, **kwargs):
            # Don't actually save the model, convert to an add() call instead
            obj = getattr(self, model_module_name)
            manager = getattr(obj, field.name)
            manager.add(getattr(self, to_module_name))
            obj.save()  # must save parent model because Django admin won't

        def delete(self, *args, **kwargs):
            # Don't actually delete the model, convert to a delete() call instead
            obj = getattr(self, model_module_name)
            manager = getattr(obj, field.name)
            manager.remove(getattr(self, to_module_name))
            obj.save()  # must save parent model because Django admin won't

    # Remove old model from Django's model registry, because it would be a duplicate
    from django.db.models.loading import cache
    model_dict = cache.app_models.get(Through._meta.app_label)
    del model_dict[Through._meta.module_name]
    # Rename the model
    Through.__name__ = obj_name
    Through._meta.app_label = model._meta.app_label
    Through._meta.object_name = obj_name
    Through._meta.module_name = obj_name.lower()
    Through._meta.db_table = Through._meta.app_label + '_' + Through._meta.module_name
    Through._meta.verbose_name = _('%(model)s %(to)s relationship') % {
        'model': model._meta.verbose_name,
        'to': to._meta.verbose_name
    }
    Through._meta.verbose_name_plural = _('%(model)s %(to)s relationships') % {
        'model': model._meta.verbose_name,
        'to': to._meta.verbose_name
    }
    # Add new model to Django's model registry
    cache.register_models(Through._meta.app_label, Through)
    return Through
Example #11
0
def create_through(field, model, to):
    """
    Create a dummy 'through' model for MongoDBManyToMany relations. Django assumes there is a real
    database model providing the relationship, so we simulate it. This model has to have
    a ForeignKey relationship to both models. We will also override the save() and delete()
    methods to pass the adding and removing of related objects to the relation manager.
    """
    obj_name = model._meta.object_name + to._meta.object_name + 'Relationship'
    to_module_name = to._meta.module_name
    model_module_name = model._meta.module_name
    class ThroughQuerySet(object):
        def __init__(self, relationship_model, *args, **kwargs):
            self.to = to
            self.model = relationship_model
            self.model_instance = None
            self.related_manager = None
            self.to_instance = None
            self.db = 'default'
        def filter(self, *args, **kwargs):
            if model_module_name in kwargs:
                # Relation, set up for querying by the model
                self.model_instance = kwargs[model_module_name]
                self.related_manager = getattr(self.model_instance, field.name)
                # Now we know enough to retrieve the actual query set
                queryset = self.related_manager.all(appear_as_relationship=(self.model, self.model_instance, None, model_module_name, to_module_name)).using(self.db)
                return queryset
            if to_module_name in kwargs:
                # Reverse relation, set up for querying by the to model
                self.to_instance = kwargs[to_module_name]
                self.reverse_manager = getattr(self.to_instance, field.rel.related_name)
                queryset = self.reverse_manager._relationship_query_set(self.model, self.to_instance, model_module_name, to_module_name).using(self.db)
                return queryset
            return self
        def exists(self, *args, **kwargs):
            return False
        def ordered(self, *args, **kwargs):
            return self
        def using(self, db, *args, **kwargs):
            self.db = db
            return self
        def get(self, *args, **kwargs):
            # Check if it's a magic key
            if 'pk' in kwargs and isinstance(kwargs['pk'], basestring) and '$' in kwargs['pk']:
                model_id, direction, to_id = kwargs['pk'].split('$', 2)
                if direction == 'r':
                    # It's a reverse magic key
                    to_id, model_id = model_id, to_id
                if direction == 'r':
                    # Query in reverse
                    self.to_instance = self.to.objects.get(pk=to_id)
                    self.reverse_manager = getattr(self.to_instance, field.rel.related_name)
                    queryset = self.reverse_manager._relationship_query_set(self.model, self.to_instance, model_module_name, to_module_name).using(self.db)
                    obj = queryset.get(pk=model_id)
                    return obj
                else:
                    self.model_instance = model.objects.get(pk=model_id)
                    self.related_manager = getattr(self.model_instance, field.name)
                    queryset = self.related_manager.all(appear_as_relationship=(self.model, self.model_instance, None, model_module_name, to_module_name)).using(self.db)
                    return queryset.get(pk=to_id)
            # Normal key
            return None
        def __len__(self):
            # Won't work, must be accessed through filter()
            raise Exception('ThroughQuerySet relation unknown (__len__)')
        def __getitem__(self, key):
            # Won't work, must be accessed through filter()
            raise Exception('ThroughQuerySet relation unknown (__getitem__)')
    class ThroughManager(MongoDBManager):
        def get_query_set(self):
            return ThroughQuerySet(self.model)
    class Through(models.Model):
        class Meta:
            auto_created = model
        objects = ThroughManager()
        locals()[to_module_name] = models.ForeignKey(to, null=True, blank=True)
        locals()[model_module_name] = models.ForeignKey(model, null=True, blank=True)
        def __unicode__(self):
            return unicode(getattr(self, model_module_name)) + u' : ' + unicode(getattr(self, to_module_name))
        def save(self, *args, **kwargs):
            # Don't actually save the model, convert to an add() call instead
            obj = getattr(self, model_module_name)
            manager = getattr(obj, field.name)
            manager.add(getattr(self, to_module_name))
            obj.save() # must save parent model because Django admin won't
        def delete(self, *args, **kwargs):
            # Don't actually delete the model, convert to a delete() call instead
            obj = getattr(self, model_module_name)
            manager = getattr(obj, field.name)
            manager.remove(getattr(self, to_module_name))
            obj.save() # must save parent model because Django admin won't
    # Remove old model from Django's model registry, because it would be a duplicate
    from django.db.models.loading import cache
    model_dict = cache.app_models.get(Through._meta.app_label)
    del model_dict[Through._meta.module_name]
    # Rename the model
    Through.__name__ = obj_name
    Through._meta.app_label = model._meta.app_label
    Through._meta.object_name = obj_name
    Through._meta.module_name = obj_name.lower()
    Through._meta.db_table = Through._meta.app_label + '_' + Through._meta.module_name
    Through._meta.verbose_name = _('%(model)s %(to)s relationship') % {'model':model._meta.verbose_name, 'to':to._meta.verbose_name}
    Through._meta.verbose_name_plural = _('%(model)s %(to)s relationships') % {'model':model._meta.verbose_name, 'to':to._meta.verbose_name}
    # Add new model to Django's model registry
    cache.register_models(Through._meta.app_label, Through)
    return Through