Python django.db.models.Model() Examples

The following are code examples for showing how to use django.db.models.Model(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: eventsourcing   Author: johnbywater   File: test_process_with_django.py    BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def define_projection_record_class(self):
        class ProjectionRecord(models.Model):
            uid = models.BigAutoField(primary_key=True)

            # Sequence ID (e.g. an entity or aggregate ID).
            projection_id = models.UUIDField()

            # State of the item (serialized dict, possibly encrypted).
            state = models.TextField()

            class Meta:
                db_table = "projections"
                app_label = "projections"
                managed = False

        self.projection_record_class = ProjectionRecord 
Example 2
Project: xadmin_bugfix   Author: vip68   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 3
Project: xadmin_bugfix   Author: vip68   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example 4
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 5
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example 6
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 7
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example 8
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 9
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_field_from_model_factory_error_message():
    from django.db.models import Field as DjangoField, Model

    class CustomField(DjangoField):
        pass

    class FooModel(Model):
        foo = CustomField()

    with pytest.raises(AssertionError) as error:
        Field.from_model(FooModel, 'foo')

    acceptable_error_messages = [
        "No factory for <class 'tests.test_forms.CustomField'>. Register a factory with register_field_factory, you can also register one that returns None to not handle this field type",
        "No factory for <class 'tests.test_forms.test_field_from_model_factory_error_message.<locals>.CustomField'>. Register a factory with register_field_factory, you can also register one that returns None to not handle this field type",
    ]
    assert str(error.value) in acceptable_error_messages 
Example 10
Project: django-entangled   Author: jrief   File: forms.py    MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        opts = self._meta
        if 'instance' in kwargs and kwargs['instance']:
            initial = kwargs['initial'] if 'initial' in kwargs else {}
            for field_name, assigned_fields in opts.entangled_fields.items():
                reference = getattr(kwargs['instance'], field_name)
                for af in assigned_fields:
                    if af in reference:
                        if isinstance(self.base_fields[af], ModelMultipleChoiceField):
                            try:
                                Model = apps.get_model(reference[af]['model'])
                                initial[af] = Model.objects.filter(pk__in=reference[af]['p_keys'])
                            except (KeyError, TypeError):
                                pass
                        elif isinstance(self.base_fields[af], ModelChoiceField):
                            try:
                                Model = apps.get_model(reference[af]['model'])
                                initial[af] = Model.objects.get(pk=reference[af]['pk'])
                            except (KeyError, ObjectDoesNotExist, TypeError):
                                pass
                        else:
                            initial[af] = reference[af]
            kwargs.setdefault('initial', initial)
        super().__init__(*args, **kwargs) 
Example 11
Project: django-entangled   Author: jrief   File: forms.py    MIT License 6 votes vote down vote up
def _clean_form(self):
        opts = self._meta
        super()._clean_form()
        cleaned_data = {f: self.cleaned_data[f] for f in opts.untangled_fields if f in self.cleaned_data}
        for field_name, assigned_fields in opts.entangled_fields.items():
            cleaned_data[field_name] = {}
            for af in assigned_fields:
                if af not in self.cleaned_data:
                    continue
                if isinstance(self.base_fields[af], ModelMultipleChoiceField) and isinstance(self.cleaned_data[af], QuerySet):
                    opts = self.cleaned_data[af].model._meta
                    cleaned_data[field_name][af] = {
                        'model': '{}.{}'.format(opts.app_label, opts.model_name),
                        'p_keys': list(self.cleaned_data[af].values_list('pk', flat=True)),
                    }
                elif isinstance(self.base_fields[af], ModelChoiceField) and isinstance(self.cleaned_data[af], Model):
                    opts = self.cleaned_data[af]._meta
                    cleaned_data[field_name][af] = {
                        'model': '{}.{}'.format(opts.app_label, opts.model_name),
                        'pk': self.cleaned_data[af].pk,
                    }
                else:
                    cleaned_data[field_name][af] = self.cleaned_data[af]
        self.cleaned_data = cleaned_data 
Example 12
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 6 votes vote down vote up
def deconstruct(self):
        kwargs = {
            'name': self.name,
            'fields': self.fields,
        }
        if self.options:
            kwargs['options'] = self.options
        if self.bases and self.bases != (models.Model,):
            kwargs['bases'] = self.bases
        if self.managers and self.managers != [('objects', models.Manager())]:
            kwargs['managers'] = self.managers
        return (
            self.__class__.__name__,
            [],
            kwargs
        ) 
Example 13
Project: chattR   Author: patrickstocklin   File: utils.py    GNU General Public License v2.0 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 14
Project: chattR   Author: patrickstocklin   File: validation.py    GNU General Public License v2.0 6 votes vote down vote up
def validate_inlines(self, cls, model):
        " Validate inline model admin classes. "
        from django.contrib.admin.options import BaseModelAdmin
        if hasattr(cls, 'inlines'):
            check_isseq(cls, 'inlines', cls.inlines)
            for idx, inline in enumerate(cls.inlines):
                if not issubclass(inline, BaseModelAdmin):
                    raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit "
                            "from BaseModelAdmin." % (cls.__name__, idx))
                if not inline.model:
                    raise ImproperlyConfigured("'model' is a required attribute "
                            "of '%s.inlines[%d]'." % (cls.__name__, idx))
                if not issubclass(inline.model, models.Model):
                    raise ImproperlyConfigured("'%s.inlines[%d].model' does not "
                            "inherit from models.Model." % (cls.__name__, idx))
                inline.validate(inline.model)
                self.check_inline(inline, model) 
Example 15
Project: opadmin   Author: cc0411   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 16
Project: opadmin   Author: cc0411   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example 17
Project: StormOnline   Author: stormsha   File: util.py    Apache License 2.0 6 votes vote down vote up
def model_format_dict(obj):
    """
    Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
    typically for use with string formatting.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.

    """
    if isinstance(obj, (models.Model, models.base.ModelBase)):
        opts = obj._meta
    elif isinstance(obj, models.query.QuerySet):
        opts = obj.model._meta
    else:
        opts = obj
    return {
        'verbose_name': force_text(opts.verbose_name),
        'verbose_name_plural': force_text(opts.verbose_name_plural)
    } 
Example 18
Project: StormOnline   Author: stormsha   File: util.py    Apache License 2.0 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example 19
Project: aas   Author: Uninett   File: mappings.py    GNU General Public License v3.0 6 votes vote down vote up
def validate_field_mappings(model: Type[models.Model], field_mappings: dict):
    for field_name, field_value_getter in field_mappings.items():
        if not hasattr(model, field_name):
            raise ValueError(f"{model} has no attribute '{field_name}'")

        if type(field_value_getter) is PassthroughField:
            if model._meta.get_field(field_name).is_relation:
                raise ValueError(
                    f"The field {field_name} is a relational field and cannot be paired up with a PassthroughField."
                )
        elif type(field_value_getter) is ForeignKeyField:
            if not model._meta.get_field(field_name).is_relation:
                raise ValueError(
                    f"The field {field_name} is not a relational field and cannot be paired up with a ForeignKeyField."
                )
        elif field_value_getter is not None:
            raise ValueError(
                "The type of the values of the dicts must either be an instance of FieldValueGetter or None,"
                f" not {type(field_value_getter)}."
            ) 
Example 20
Project: munch-core   Author: crunchmail   File: models.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def update_mail_status(self):
        try:
            self.mail.curstatus = self.status
            if not self.pk and not self.creation_date:
                self.creation_date = timezone.now()

            if not self.mail.first_status_date:
                self.mail.first_status_date = self.creation_date
            self.mail.latest_status_date = self.creation_date
            self.mail.delivery_duration = self.mail.latest_status_date \
                - self.mail.first_status_date
            # a mail had issues if it had been softbounced at a certain time.
            self.mail.had_delay = self.mail.had_delay or (
                self.status == AbstractMailStatus.DROPPED)
            # warning : save_base_is not part of the public Django API
            models.Model.save_base(self.mail)
        except self.mail.DoesNotExist:
            pass 
Example 21
Project: TESTGIT   Author: B-ROY   File: util.py    Apache License 2.0 6 votes vote down vote up
def model_ngettext(obj, n=None):
    """
    Return the appropriate `verbose_name` or `verbose_name_plural` value for
    `obj` depending on the count `n`.

    `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
    If `obj` is a `QuerySet` instance, `n` is optional and the length of the
    `QuerySet` is used.

    """
    if isinstance(obj, models.query.QuerySet):
        if n is None:
            n = obj.count()
        obj = obj.model
    d = model_format_dict(obj)
    singular, plural = d["verbose_name"], d["verbose_name_plural"]
    return ungettext(singular, plural, n or 0) 
Example 22
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 6 votes vote down vote up
def validate_inlines(self, cls, model):
        " Validate inline model admin classes. "
        from django.contrib.admin.options import BaseModelAdmin
        if hasattr(cls, 'inlines'):
            check_isseq(cls, 'inlines', cls.inlines)
            for idx, inline in enumerate(cls.inlines):
                if not issubclass(inline, BaseModelAdmin):
                    raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit "
                            "from BaseModelAdmin." % (cls.__name__, idx))
                if not inline.model:
                    raise ImproperlyConfigured("'model' is a required attribute "
                            "of '%s.inlines[%d]'." % (cls.__name__, idx))
                if not issubclass(inline.model, models.Model):
                    raise ImproperlyConfigured("'%s.inlines[%d].model' does not "
                            "inherit from models.Model." % (cls.__name__, idx))
                inline.validate(inline.model)
                self.check_inline(inline, model) 
Example 23
Project: django-rest-polymorphic   Author: apirobot   File: serializers.py    MIT License 5 votes vote down vote up
def _to_model(self, model_or_instance):
        return (model_or_instance.__class__
                if isinstance(model_or_instance, models.Model)
                else model_or_instance) 
Example 24
Project: autolims   Author: scottbecker   File: models.py    MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        
        if self.transcriptic_id == '':
            self.transcriptic_id = None
    
        if not isinstance(self.sensitivities,list):
            self.sensitivities = []           
    
        if not isinstance(self.properties,dict):
            self.properties = []          
    
        super(Resource, self).save(*args, **kwargs)    
    
    
    
#@python_2_unicode_compatible
#class Kit(models.Model):
#https://secure.transcriptic.com/_commercial/kits?format=json

#@python_2_unicode_compatible
#class KitItem(models.Model):
#https://secure.transcriptic.com/_commercial/kits/kit19jybkyf8ddv/kit_items?format=json
    

    
# This code is triggered whenever a new user has been created and saved to the database 
Example 25
Project: django-click   Author: GaretJax   File: params.py    MIT License 5 votes vote down vote up
def __init__(self, qs, lookup='pk'):
        from django.db import models

        if isinstance(qs, type) and issubclass(qs, models.Model):
            qs = qs.objects.all()
        self.qs = qs
        self.name = '{}.{}'.format(
            qs.model._meta.app_label,
            qs.model.__name__,
        )
        self.lookup = lookup 
Example 26
Project: Servo   Author: fpsw   File: forms.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def serialize(self):
        import datetime
        from django.db.models import Model
        cd = self.cleaned_data

        for k, v in cd.iteritems():
            if isinstance(v, datetime.datetime):
                cd[k] = str(v)
            if isinstance(v, Model):
                cd[k] = v.pk

        return cd 
Example 27
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_concrete_class_for_model_field(cls, model_field):
        """
        Method for getting a concrete model class to represent the type of form field required

        :param model_field: Model Field instance
        :return: OmniField subclass
        """
        field_mapping = {
            models.CharField: OmniCharField,
            models.TextField: OmniCharField,
            models.BooleanField: OmniBooleanField,
            models.NullBooleanField: OmniBooleanField,
            models.DateField: OmniDateField,
            models.DateTimeField: OmniDateTimeField,
            models.DecimalField: OmniDecimalField,
            models.EmailField: OmniEmailField,
            models.FloatField: OmniFloatField,
            models.IntegerField: OmniIntegerField,
            models.BigIntegerField: OmniIntegerField,
            models.PositiveIntegerField: OmniIntegerField,
            models.PositiveSmallIntegerField: OmniIntegerField,
            models.SmallIntegerField: OmniIntegerField,
            models.CommaSeparatedIntegerField: OmniCharField,
            models.TimeField: OmniTimeField,
            models.URLField: OmniUrlField,
            models.ForeignKey: OmniForeignKeyField,
            models.ManyToManyField: OmniManyToManyField,
            models.SlugField: OmniSlugField,
            models.FileField: OmniFileField,
            models.ImageField: OmniImageField,
            models.DurationField: OmniDurationField,
            models.GenericIPAddressField: OmniGenericIPAddressField
        }
        field_mapping.update(cls.get_custom_field_mapping())
        return field_mapping.get(model_field.__class__) 
Example 28
Project: mezzanine-smartling   Author: Appdynamics   File: managers.py    Apache License 2.0 5 votes vote down vote up
def get_followed_relations(self, obj):
        """Returns an iterable of related models that should be included in the revision data."""
        for relationship in self.follow:
            # Clear foreign key cache.
            try:
                related_field = obj._meta.get_field(relationship)
            except models.FieldDoesNotExist:
                pass
            else:
                if isinstance(related_field, models.ForeignKey):
                    if hasattr(obj, related_field.get_cache_name()):
                        delattr(obj, related_field.get_cache_name())
            # Get the referenced obj(s).
            try:
                related = getattr(obj, relationship)
            except ObjectDoesNotExist:
                continue
            if isinstance(related, models.Model):
                yield related
            elif isinstance(related, (models.Manager, QuerySet)):
                for related_obj in related.all():
                    yield related_obj
            elif related is not None:
                raise TypeError("Cannot follow the relationship {relationship}. Expected a model or QuerySet, found {related}".format(
                    relationship = relationship,
                    related = related,
                )) 
Example 29
Project: mezzanine-smartling   Author: Appdynamics   File: managers.py    Apache License 2.0 5 votes vote down vote up
def get_followed_relations(self, obj):
        """Returns an iterable of related models that should be included in the revision data."""
        for relationship in self.follow:
            # Clear foreign key cache.
            try:
                related_field = obj._meta.get_field(relationship)
            except models.FieldDoesNotExist:
                pass
            else:
                if isinstance(related_field, models.ForeignKey):
                    if hasattr(obj, related_field.get_cache_name()):
                        delattr(obj, related_field.get_cache_name())
            # Get the referenced obj(s).
            try:
                related = getattr(obj, relationship)
            except ObjectDoesNotExist:
                continue
            if isinstance(related, models.Model):
                yield related
            elif isinstance(related, (models.Manager, QuerySet)):
                for related_obj in related.all():
                    yield related_obj
            elif related is not None:
                raise TypeError("Cannot follow the relationship {relationship}. Expected a model or QuerySet, found {related}".format(
                    relationship = relationship,
                    related = related,
                )) 
Example 30
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_create_empty_instance(self):
        def create():
            from echoices.enums import EChoice

            class ETestComplexChoices(EChoice):
                FIELD1 = (1 + 1j, 'Label 1')
                FIELD2 = (2 + 1j, 'Label 2')

            from django.db import models
            class TestEChoiceFieldEComplexChoicesModel(models.Model):
                from echoices.fields import make_echoicefield
                choice = make_echoicefield(ETestComplexChoices, default=ETestComplexChoices.FIELD1)

        self.assertRaises(NotImplementedError, create) 
Example 31
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_create_empty_instance(self):
        def create():
            from django.db import models

            class TestEChoiceFieldMixedDefaultModel(models.Model):
                from echoices.fields import make_echoicefield
                choice = make_echoicefield(ETestCharChoices, default=ETestIntChoices.FIELD1)

        self.assertRaises(AttributeError, create) 
Example 32
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_from_model_required():
    from django.db.models import TextField, Model

    class FooModel(Model):
        a = TextField(blank=True, null=True)
        b = TextField(blank=True, null=False)
        c = TextField(blank=False, null=True)
        d = TextField(blank=False, null=False)

    assert not Field.from_model(FooModel, 'a').required
    assert not Field.from_model(FooModel, 'b').required
    assert not Field.from_model(FooModel, 'c').required
    assert Field.from_model(FooModel, 'd').required 
Example 33
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_from_model_label():
    from django.db.models import TextField, Model

    class FooModel(Model):
        a = TextField(verbose_name='FOOO bar FOO')

    assert Field.from_model(FooModel, 'a').display_name == 'FOOO bar FOO' 
Example 34
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_null_field_factory():
    from django.db import models

    class ShouldBeNullField(models.Field):
        pass

    class FooModel(models.Model):
        should_be_null = ShouldBeNullField()
        foo = models.IntegerField()

    register_field_factory(ShouldBeNullField, None)

    form = Form.from_model(data=None, model=FooModel)
    assert list(form.fields_by_name.keys()) == ['foo'] 
Example 35
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_choice_queryset_ajax_attrs_foreign_key(kwargs):
    from django.contrib.auth.models import User
    from django.db import models
    from django.db.models import CASCADE

    class FooModel(models.Model):
        user = models.ForeignKey(User, on_delete=CASCADE)

    User.objects.create(username='foo')
    user2 = User.objects.create(username='bar')

    form = Form.from_model(model=FooModel, data={}, **kwargs)
    form.request = RequestFactory().get('/')
    assert form.endpoint_dispatch(key='field/user', value='ar') == dict(results=[{'id': user2.pk, 'text': smart_str(user2)}], more=False, page=1) 
Example 36
Project: django-entangled   Author: jrief   File: forms.py    MIT License 5 votes vote down vote up
def get_related_object(scope, field_name):
    """
    Returns the related field, referenced by the content of a ModelChoiceField.
    """
    try:
        Model = apps.get_model(scope[field_name]['model'])
        relobj = Model.objects.get(pk=scope[field_name]['pk'])
    except:
        relobj = None
    return relobj 
Example 37
Project: django-entangled   Author: jrief   File: forms.py    MIT License 5 votes vote down vote up
def get_related_queryset(scope, field_name):
    """
    Returns the related queryset, referenced by the content of a ModelChoiceField.
    """
    try:
        Model = apps.get_model(scope[field_name]['model'])
        queryset = Model.objects.filter(pk__in=scope[field_name]['p_keys'])
    except (KeyError, TypeError):
        queryset = None
    return queryset 
Example 38
Project: djing   Author: nerosketch   File: acc_tags.py    The Unlicense 5 votes vote down vote up
def klass_name(klass):
    if type(klass) is class_types and issubclass(klass, Model):
        kl = klass
    elif isinstance(klass, string_types):
        app_label, model_name = klass.split('.', 1)
        kl = apps.get_model(app_label, model_name)
    else:
        return 'Type not detected'
    return kl._meta.verbose_name 
Example 39
Project: chattR   Author: patrickstocklin   File: detail.py    GNU General Public License v2.0 5 votes vote down vote up
def get_context_object_name(self, obj):
        """
        Get the name to use for the object.
        """
        if self.context_object_name:
            return self.context_object_name
        elif isinstance(obj, models.Model):
            return obj._meta.model_name
        else:
            return None 
Example 40
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, name, fields, options=None, bases=None, managers=None):
        self.name = name
        self.fields = fields
        self.options = options or {}
        self.bases = bases or (models.Model,)
        self.managers = managers or [] 
Example 41
Project: chattR   Author: patrickstocklin   File: state.py    GNU General Public License v2.0 5 votes vote down vote up
def get_related_models_recursive(model):
    """
    Returns all models that have a direct or indirect relationship
    to the given model.

    Relationships are either defined by explicit relational fields, like
    ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another
    model (a superclass is related to its subclasses, but not vice versa). Note,
    however, that a model inheriting from a concrete model is also related to
    its superclass through the implicit *_ptr OneToOneField on the subclass.
    """
    def _related_models(m):
        return [
            f.related_model for f in m._meta.get_fields(include_parents=True, include_hidden=True)
            if f.is_relation and not isinstance(f.related_model, six.string_types)
        ] + [
            subclass for subclass in m.__subclasses__()
            if issubclass(subclass, models.Model)
        ]

    seen = set()
    queue = _related_models(model)
    for rel_mod in queue:
        rel_app_label, rel_model_name = rel_mod._meta.app_label, rel_mod._meta.model_name
        if (rel_app_label, rel_model_name) in seen:
            continue
        seen.add((rel_app_label, rel_model_name))
        queue.extend(_related_models(rel_mod))
    return seen - {(model._meta.app_label, model._meta.model_name)} 
Example 42
Project: chattR   Author: patrickstocklin   File: state.py    GNU General Public License v2.0 5 votes vote down vote up
def render(self, apps):
        "Creates a Model object from our current state into the given apps"
        # First, make a Meta object
        meta_contents = {'app_label': self.app_label, "apps": apps}
        meta_contents.update(self.options)
        meta = type(str("Meta"), tuple(), meta_contents)
        # Then, work out our bases
        try:
            bases = tuple(
                (apps.get_model(base) if isinstance(base, six.string_types) else base)
                for base in self.bases
            )
        except LookupError:
            raise InvalidBasesError("Cannot resolve one or more bases from %r" % (self.bases,))
        # Turn fields into a dict for the body, add other bits
        body = dict(self.construct_fields())
        body['Meta'] = meta
        body['__module__'] = "__fake__"

        # Restore managers
        body.update(self.construct_managers())

        # Then, make a Model object (apps.register_model is called in __new__)
        return type(
            str(self.name),
            bases,
            body,
        ) 
Example 43
Project: chattR   Author: patrickstocklin   File: checks.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_inlines_item(self, cls, model, inline, label):
        """ Check one inline model admin. """
        inline_label = '.'.join([inline.__module__, inline.__name__])

        from django.contrib.admin.options import BaseModelAdmin

        if not issubclass(inline, BaseModelAdmin):
            return [
                checks.Error(
                    "'%s' must inherit from 'BaseModelAdmin'." % inline_label,
                    hint=None,
                    obj=cls,
                    id='admin.E104',
                )
            ]
        elif not inline.model:
            return [
                checks.Error(
                    "'%s' must have a 'model' attribute." % inline_label,
                    hint=None,
                    obj=cls,
                    id='admin.E105',
                )
            ]
        elif not issubclass(inline.model, models.Model):
            return must_be('a Model', option='%s.model' % inline_label,
                           obj=cls, id='admin.E106')
        else:
            return inline.check(model) 
Example 44
Project: djexp   Author: Djangolify   File: module.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, m_name: str, settings_module: str):
		environ.setdefault('DJANGO_SETTINGS_MODULE', settings_module)
		django.setup()
		self.__module = import_module(m_name)
		classes = [Class(cls[1]) for cls in self.members(inspect.isclass) if cls[1].__module__ == self.__module.__name__]
		self.__classes = [cls for cls in classes if Model in cls.bases] 
Example 45
Project: django-boost   Author: ChanTsune   File: sites.py    MIT License 5 votes vote down vote up
def register_all(models, admin_class=admin.ModelAdmin):
    for attr in dir(models):
        attr = getattr(models, attr, None)
        if isinstance(attr, type):
            if issubclass(attr, Model) and not attr._meta.abstract:
                try:
                    admin.site.register(attr, admin_class)
                except admin.sites.AlreadyRegistered:
                    pass 
Example 46
Project: django-boost   Author: ChanTsune   File: functions.py    MIT License 5 votes vote down vote up
def model_to_json(model, fields=(), exclude=()):
    """
    Take Model or Model.QuerySet as an argument.

    Return value is a dictionary or a list for dictionary.
    """
    if isinstance(model, models.Model):
        json_data = {}

        if fields:
            for f in fields:
                json_data[f] = getattr(model, f)
            return json_data

        elif exclude:
            for f in model._meta.fields:
                if f.name not in exclude:
                    json_data[f.name] = getattr(model, f.name)
            return json_data

        else:
            for f in model._meta.fields:
                json_data[f.name] = getattr(model, f.name)
            return json_data

    elif isinstance(model, models.QuerySet):
        json_data = [model_to_json(m, fields, exclude) for m in model]
        return json_data

    raise TypeError('argument must be {} or {}'.format(
        models.Model, models.QuerySet)) 
Example 47
Project: django-rest-registration   Author: apragacz   File: checks.py    MIT License 5 votes vote down vote up
def _are_login_fields_unique() -> bool:
    user_cls = get_user_model()  # type: Type[Model]
    user_meta = user_cls._meta  # pylint: disable=protected-access
    return all(
        is_model_field_unique(user_meta.get_field(field_name))
        for field_name in get_user_login_field_names()) 
Example 48
Project: django-verification-token   Author: druids   File: models.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def filter_active_tokens(self, obj_or_class, slug=None, key=None):
        qs = self.filter(
            is_active=True,
            slug=slug,
            content_type=ContentType.objects.get_for_model(obj_or_class),
        )
        if isinstance(obj_or_class, models.Model):
            qs = qs.filter(object_id=obj_or_class.pk)
        return qs.filter(key=key) if key else qs 
Example 49
Project: tg-apicore   Author: thorgate   File: serializers.py    ISC License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # If we have an existing instance, mark the create-only fields as read-only.
        if not getattr(self, 'many', False) and isinstance(self.instance, Model) and self.instance.pk is not None:
            create_only_fields = getattr(self.Meta, 'create_only_fields', [])
            for field_name in create_only_fields:
                self.fields[field_name].read_only = True 
Example 50
Project: drf-flex-fields   Author: rsinger86   File: filter_backends.py    MIT License 5 votes vote down vote up
def _get_field(field_name: str, model: models.Model) -> Optional[models.Field]:
        try:
            # noinspection PyProtectedMember
            return model._meta.get_field(field_name)
        except models.FieldDoesNotExist:
            return None 
Example 51
Project: cobweb-django   Author: CobwebOrg   File: cobweb_look.py    MIT License 5 votes vote down vote up
def as_link(item: Model) -> dict:
    url = item.get_absolute_url()
    if bool(urlsplit(url).netloc):
        # True for absolute URLs
        link_icon = ' ' + icon('external-link')
    else:
        link_icon = ''

    return mark_safe(f'<a href="{url}">{item}{link_icon}</a>') 
Example 52
Project: cobweb-django   Author: CobwebOrg   File: cobweb_look.py    MIT License 5 votes vote down vote up
def model(item):
    model = None
    if isclass(item) and issubclass(item, Model):
        model = item
    elif isinstance(item, Model):
        model = type(item)
    elif isinstance(item, SearchResult):
        model = item.model
    else:
        raise ValueError(f"Filter cobweb_look.model can't handle type: {type(item)}")
    return model 
Example 53
Project: aas   Author: Uninett   File: mappings.py    GNU General Public License v3.0 5 votes vote down vote up
def prepare(self, field_name: str, model_for_field: Type[models.Model]):
        """
        Must be called before setting any fields.
        """
        pass 
Example 54
Project: aas   Author: Uninett   File: mappings.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(
        self, foreign_model: Type[models.Model], foreign_model_field_mappings: dict
    ):
        MappingUtils.remove_none_mappings(foreign_model_field_mappings)
        MappingUtils.swap_fields_with_field_names(foreign_model_field_mappings)
        validate_field_mappings(foreign_model, foreign_model_field_mappings)

        self.foreign_model = foreign_model
        self.foreign_model_field_mappings = foreign_model_field_mappings 
Example 55
Project: aas   Author: Uninett   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def prepare_field_value_getters(model: Type[models.Model], field_mappings: dict):
        for field_name, field_value_getter in field_mappings.items():
            field_value_getter.prepare(field_name, model) 
Example 56
Project: aas   Author: Uninett   File: generate_fixtures.py    GNU General Public License v3.0 5 votes vote down vote up
def set_pks(model_objects: List[Model]) -> List[Model]:
    pk = START_PK
    for obj in model_objects:
        obj.pk = pk
        pk += 1
    return model_objects


# --- Generation functions --- 
Example 57
Project: aas   Author: Uninett   File: generate_fixtures.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_object_types() -> List[Model]:
    object_types = []
    for _ in range(NUM_OBJECT_TYPES):
        object_types.append(
            ObjectType(name=random_word(OBJECT_TYPE_NAME_LENGTH_RANGE).title())
        )

    return set_pks(object_types) 
Example 58
Project: aas   Author: Uninett   File: generate_fixtures.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_parent_objects(network_systems) -> List[Model]:
    parent_objects = []
    for _ in range(NUM_PARENT_OBJECTS):
        network_system = random.choice(network_systems)
        name = random_words(PARENT_OBJECT_NAME_WORD_COUNT_RANGE).title()

        parent_objects.append(
            ParentObject(
                name=name,
                parentobject_id=random_id(),
                url=format_url(network_system, name),
            )
        )

    return set_pks(parent_objects) 
Example 59
Project: aas   Author: Uninett   File: generate_fixtures.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_problem_types() -> List[Model]:
    problem_types = []
    for _ in range(NUM_PROBLEM_TYPES):
        name = "".join(
            w.title() for w in random_word_list(PROBLEM_TYPE_NAME_WORD_COUNT_RANGE)
        )
        # Make first letter lower case
        name = name[0].lower() + name[1:]

        description = random_description(PROBLEM_TYPE_DESCRIPTION_WORD_COUNT_RANGE)

        problem_types.append(ProblemType(name=name, description=description))

    return set_pks(problem_types) 
Example 60
Project: aas   Author: Uninett   File: generate_fixtures.py    GNU General Public License v3.0 5 votes vote down vote up
def generate_alerts(
    network_systems, objects, parent_objects, problem_types
) -> List[Model]:
    second_delay = timedelta(seconds=1)

    alerts = []
    for i in range(NUM_ALERTS):
        if roll_dice(ALERT_TIMESTAMP_NOW_CHANCE):
            # Adds a small delay between each alert with a "now" timestamp
            timestamp = timezone.now() + i * second_delay
        else:
            timestamp = random_timestamp()

        network_system = random.choice(network_systems)
        alert_id = random_id()

        alerts.append(
            Alert(
                timestamp=timestamp,
                source=network_system,
                alert_id=alert_id,
                object=random.choice(objects),
                parent_object=random.choice(parent_objects),
                details_url=format_url(network_system, alert_id),
                problem_type=random.choice(problem_types),
                description=random_description(ALERT_DESCRIPTION_WORD_COUNT_RANGE),
            )
        )

    return set_pks(alerts) 
Example 61
Project: wagtailinvoices   Author: SableWalnut   File: models.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_invoice_model(cls):
        if isinstance(cls.invoice_model, models.Model):
            return cls.invoice_model
        elif isinstance(cls.invoice_model, string_types):
            return resolve_model_string(cls.invoice_model, cls._meta.app_label)
        else:
            raise ValueError('Can not resolve {0}.invoice_model in to a model: {1!r}'.format(
                cls.__name__, cls.invoice_model)) 
Example 62
Project: TESTGIT   Author: B-ROY   File: detail.py    Apache License 2.0 5 votes vote down vote up
def get_context_object_name(self, obj):
        """
        Get the name to use for the object.
        """
        if self.context_object_name:
            return self.context_object_name
        elif isinstance(obj, models.Model):
            return obj._meta.model_name
        else:
            return None 
Example 63
Project: TESTGIT   Author: B-ROY   File: managers.py    Apache License 2.0 5 votes vote down vote up
def for_model(self, model):
        """
        QuerySet for all comments for a particular model (either an instance or
        a class).
        """
        ct = ContentType.objects.get_for_model(model)
        qs = self.get_queryset().filter(content_type=ct)
        if isinstance(model, models.Model):
            qs = qs.filter(object_pk=force_text(model._get_pk_val()))
        return qs 
Example 64
Project: AneMo   Author: jspargo   File: detail.py    GNU General Public License v2.0 5 votes vote down vote up
def get_context_object_name(self, obj):
        """
        Get the name to use for the object.
        """
        if self.context_object_name:
            return self.context_object_name
        elif isinstance(obj, models.Model):
            return obj._meta.model_name
        else:
            return None 
Example 65
Project: AneMo   Author: jspargo   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, name, fields, options=None, bases=None):
        self.name = name
        self.fields = fields
        self.options = options or {}
        self.bases = bases or (models.Model,) 
Example 66
Project: AneMo   Author: jspargo   File: state.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, app_label, name, fields, options=None, bases=None):
        self.app_label = app_label
        self.name = force_text(name)
        self.fields = fields
        self.options = options or {}
        self.bases = bases or (models.Model, )
        # Sanity-check that fields is NOT a dict. It must be ordered.
        if isinstance(self.fields, dict):
            raise ValueError("ModelState.fields cannot be a dict - it must be a list of 2-tuples.")
        # Sanity-check that fields are NOT already bound to a model.
        for name, field in fields:
            if hasattr(field, 'model'):
                raise ValueError(
                    'ModelState.fields cannot be bound to a model - "%s" is.' % name
                ) 
Example 67
Project: django-route   Author: vinayinvicible   File: conf.py    MIT License 4 votes vote down vote up
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):
        # Grab the field list from the meta class
        fields = obj._meta.get_fields()

        for field in fields:
            if not hasattr(field, 'verbose_name'):
                continue
            if field.auto_created:
                continue
            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_str(field.help_text))
            if hasattr(field, 'choices') and field.choices:
                help_text += '. One of {}'.format(
                    '/'.join(
                        ch for ch, _ in field.get_choices(include_blank=False)
                    )
                )

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_str(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(
                u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines 
Example 68
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_get_name_field():
    from django.db.models import (
        Model,
        IntegerField,
        CharField,
        ForeignKey,
        CASCADE,
    )

    class Foo1(Model):
        a = IntegerField()
        name = CharField(max_length=255)

    class Bar1(Model):
        foo = ForeignKey(Foo1, on_delete=CASCADE)

    class Foo2(Model):
        a = IntegerField()
        fooname = CharField(max_length=255)
        name = CharField(max_length=255)

    class Bar2(Model):
        foo = ForeignKey(Foo2, on_delete=CASCADE)

    class Foo3(Model):
        name = IntegerField()
        fooname = CharField(max_length=255)

    class Bar3(Model):
        foo = ForeignKey(Foo3, on_delete=CASCADE)

    class Foo4(Model):
        fooname = CharField(max_length=255)
        barname = CharField(max_length=255)

    class Bar4(Model):
        foo = ForeignKey(Foo4, on_delete=CASCADE)

    class Foo5(Model):
        blabla = CharField(max_length=255)

    class Bar5(Model):
        foo = ForeignKey(Foo5, on_delete=CASCADE)

    class Foo6(Model):
        a = IntegerField()

    class Bar6(Model):
        foo = ForeignKey(Foo6, on_delete=CASCADE)

    assert get_name_field(Form.from_model(model=Bar1, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar2, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar3, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar4, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar5, data={}).fields_by_name.foo) == 'blabla'
    with pytest.raises(AssertionError):
        get_name_field(Form.from_model(model=Bar6, data={}).fields_by_name.foo) 
Example 69
Project: openhatch   Author: campbe13   File: revisions.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def follow_relationships(self, object_set):
        """
        Follows all the registered relationships in the given set of models to
        yield a set containing the original models plus all their related
        models.
        """
        result_set = set()
        def _follow_relationships(obj):
            # Prevent recursion.
            if obj in result_set:
                return
            result_set.add(obj)
            # Follow relations.
            registration_info = self.get_registration_info(obj.__class__)
            for relationship in registration_info.follow:
                # Clear foreign key cache.
                try:
                    related_field = obj._meta.get_field(relationship)
                except models.FieldDoesNotExist:
                    pass
                else:
                    if isinstance(related_field, models.ForeignKey):
                        if hasattr(obj, related_field.get_cache_name()):
                            delattr(obj, related_field.get_cache_name())
                # Get the referenced obj(s).
                try:
                    related = getattr(obj, relationship, None)
                except obj._meta.get_field_by_name(relationship)[0].model.DoesNotExist:
                    continue
                if isinstance(related, models.Model):
                    _follow_relationships(related) 
                elif isinstance(related, (models.Manager, QuerySet)):
                    for related_obj in related.all():
                        _follow_relationships(related_obj)
                elif related is not None:
                    raise TypeError, "Cannot follow the relationship %r. Expected a model or QuerySet, found %r." % (relationship, related)
            # If a proxy model's parent is registered, add it.
            if obj._meta.proxy:
                parent_cls = obj._meta.parents.keys()[0]
                if self.is_registered(parent_cls):
                    parent_obj = parent_cls.objects.get(pk=obj.pk)
                    _follow_relationships(parent_obj)
        map(_follow_relationships, object_set)
        return result_set 
Example 70
Project: chattR   Author: patrickstocklin   File: detail.py    GNU General Public License v2.0 4 votes vote down vote up
def get_template_names(self):
        """
        Return a list of template names to be used for the request. May not be
        called if render_to_response is overridden. Returns the following list:

        * the value of ``template_name`` on the view (if provided)
        * the contents of the ``template_name_field`` field on the
          object instance that the view is operating upon (if available)
        * ``<app_label>/<model_name><template_name_suffix>.html``
        """
        try:
            names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
        except ImproperlyConfigured:
            # If template_name isn't specified, it's not a problem --
            # we just start with an empty list.
            names = []

            # If self.template_name_field is set, grab the value of the field
            # of that name from the object; this is the most specific template
            # name, if given.
            if self.object and self.template_name_field:
                name = getattr(self.object, self.template_name_field, None)
                if name:
                    names.insert(0, name)

            # The least-specific option is the default <app>/<model>_detail.html;
            # only use this if the object in question is a model.
            if isinstance(self.object, models.Model):
                names.append("%s/%s%s.html" % (
                    self.object._meta.app_label,
                    self.object._meta.model_name,
                    self.template_name_suffix
                ))
            elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
                names.append("%s/%s%s.html" % (
                    self.model._meta.app_label,
                    self.model._meta.model_name,
                    self.template_name_suffix
                ))

            # If we still haven't managed to find any template names, we should
            # re-raise the ImproperlyConfigured to alert the user.
            if not names:
                raise

        return names 
Example 71
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 4 votes vote down vote up
def add_lazy_relation(cls, field, relation, operation):
    """
    Adds a lookup on ``cls`` when a related field is defined using a string,
    i.e.::

        class MyModel(Model):
            fk = ForeignKey("AnotherModel")

    This string can be:

        * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
          relation.

        * The name of a model (i.e "AnotherModel") to indicate another model in
          the same app.

        * An app-label and model name (i.e. "someapp.AnotherModel") to indicate
          another model in a different app.

    If the other model hasn't yet been loaded -- almost a given if you're using
    lazy relationships -- then the relation won't be set up until the
    class_prepared signal fires at the end of model initialization.

    operation is the work that must be performed once the relation can be resolved.
    """
    # Check for recursive relations
    if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
        app_label = cls._meta.app_label
        model_name = cls.__name__

    else:
        # Look for an "app.Model" relation

        if isinstance(relation, six.string_types):
            try:
                app_label, model_name = relation.split(".")
            except ValueError:
                # If we can't split, assume a model in current app
                app_label = cls._meta.app_label
                model_name = relation
        else:
            # it's actually a model class
            app_label = relation._meta.app_label
            model_name = relation._meta.object_name

    # Try to look up the related model, and if it's already loaded resolve the
    # string right away. If get_registered_model raises a LookupError, it means
    # that the related model isn't loaded yet, so we need to pend the relation
    # until the class is prepared.
    try:
        model = cls._meta.apps.get_registered_model(app_label, model_name)
    except LookupError:
        key = (app_label, model_name)
        value = (cls, field, operation)
        cls._meta.apps._pending_lookups.setdefault(key, []).append(value)
    else:
        operation(field, model, cls) 
Example 72
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 4 votes vote down vote up
def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookups,
                              raw_value):
        from django.db.models.sql.where import SubqueryConstraint, AND, OR
        root_constraint = constraint_class()
        assert len(targets) == len(sources)
        if len(lookups) > 1:
            raise exceptions.FieldError('Relation fields do not support nested lookups')
        lookup_type = lookups[0]

        def get_normalized_value(value):
            from django.db.models import Model
            if isinstance(value, Model):
                value_list = []
                for source in sources:
                    # Account for one-to-one relations when sent a different model
                    while not isinstance(value, source.model) and source.rel:
                        source = source.rel.to._meta.get_field(source.rel.field_name)
                    value_list.append(getattr(value, source.attname))
                return tuple(value_list)
            elif not isinstance(value, tuple):
                return (value,)
            return value

        is_multicolumn = len(self.related_fields) > 1
        if (hasattr(raw_value, '_as_sql') or
                hasattr(raw_value, 'get_compiler')):
            root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
                                                   [source.name for source in sources], raw_value),
                                AND)
        elif lookup_type == 'isnull':
            root_constraint.add(IsNull(targets[0].get_col(alias, sources[0]), raw_value), AND)
        elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
                                         and not is_multicolumn)):
            value = get_normalized_value(raw_value)
            for target, source, val in zip(targets, sources, value):
                lookup_class = target.get_lookup(lookup_type)
                root_constraint.add(
                    lookup_class(target.get_col(alias, source), val), AND)
        elif lookup_type in ['range', 'in'] and not is_multicolumn:
            values = [get_normalized_value(value) for value in raw_value]
            value = [val[0] for val in values]
            lookup_class = targets[0].get_lookup(lookup_type)
            root_constraint.add(lookup_class(targets[0].get_col(alias, sources[0]), value), AND)
        elif lookup_type == 'in':
            values = [get_normalized_value(value) for value in raw_value]
            for value in values:
                value_constraint = constraint_class()
                for source, target, val in zip(sources, targets, value):
                    lookup_class = target.get_lookup('exact')
                    lookup = lookup_class(target.get_col(alias, source), val)
                    value_constraint.add(lookup, AND)
                root_constraint.add(value_constraint, OR)
        else:
            raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
        return root_constraint 
Example 73
Project: chattR   Author: patrickstocklin   File: related.py    GNU General Public License v2.0 4 votes vote down vote up
def create_many_to_many_intermediary_model(field, klass):
    from django.db import models
    managed = True
    if isinstance(field.rel.to, six.string_types) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT:
        to_model = field.rel.to
        to = to_model.split('.')[-1]

        def set_managed(field, model, cls):
            field.rel.through._meta.managed = model._meta.managed or cls._meta.managed
        add_lazy_relation(klass, field, to_model, set_managed)
    elif isinstance(field.rel.to, six.string_types):
        to = klass._meta.object_name
        to_model = klass
        managed = klass._meta.managed
    else:
        to = field.rel.to._meta.object_name
        to_model = field.rel.to
        managed = klass._meta.managed or to_model._meta.managed
    name = '%s_%s' % (klass._meta.object_name, field.name)
    if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name:
        from_ = 'from_%s' % to.lower()
        to = 'to_%s' % to.lower()
    else:
        from_ = klass._meta.model_name
        to = to.lower()
    meta = type(str('Meta'), (object,), {
        'db_table': field._get_m2m_db_table(klass._meta),
        'managed': managed,
        'auto_created': klass,
        'app_label': klass._meta.app_label,
        'db_tablespace': klass._meta.db_tablespace,
        'unique_together': (from_, to),
        'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
        'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
        'apps': field.model._meta.apps,
    })
    # Construct and return the new class.
    return type(str(name), (models.Model,), {
        'Meta': meta,
        '__module__': klass.__module__,
        from_: models.ForeignKey(
            klass,
            related_name='%s+' % name,
            db_tablespace=field.db_tablespace,
            db_constraint=field.rel.db_constraint,
        ),
        to: models.ForeignKey(
            to_model,
            related_name='%s+' % name,
            db_tablespace=field.db_tablespace,
            db_constraint=field.rel.db_constraint,
        )
    }) 
Example 74
Project: resolwe   Author: genialis   File: __init__.py    Apache License 2.0 4 votes vote down vote up
def dict_dot(d, k, val=None, default=None):
    """Get or set value using a dot-notation key in a multilevel dict."""
    if val is None and k == '':
        return d

    def set_default(dict_or_model, key, default_value):
        """Set default field value."""
        if isinstance(dict_or_model, models.Model):
            if not hasattr(dict_or_model, key):
                setattr(dict_or_model, key, default_value)

            return getattr(dict_or_model, key)
        else:
            return dict_or_model.setdefault(key, default_value)

    def get_item(dict_or_model, key):
        """Get field value."""
        if isinstance(dict_or_model, models.Model):
            return getattr(dict_or_model, key)
        else:
            return dict_or_model[key]

    def set_item(dict_or_model, key, value):
        """Set field value."""
        if isinstance(dict_or_model, models.Model):
            setattr(dict_or_model, key, value)
        else:
            dict_or_model[key] = value

    if val is None and callable(default):
        # Get value, default for missing
        return functools.reduce(lambda a, b: set_default(a, b, default()), k.split('.'), d)

    elif val is None:
        # Get value, error on missing
        return functools.reduce(get_item, k.split('.'), d)

    else:
        # Set value
        try:
            k, k_last = k.rsplit('.', 1)
            set_item(dict_dot(d, k, default=dict), k_last, val)
        except ValueError:
            set_item(d, k, val)
        return val 
Example 75
Project: aas   Author: Uninett   File: generate_fixtures.py    GNU General Public License v3.0 4 votes vote down vote up
def generate_objects(object_types, network_systems) -> List[Model]:
    def random_object_word() -> str:
        # Will most often be an empty string, sometimes a single digit, and rarely a double digit
        suffix = (
            (
                random.choice(digits)
                + (
                    random.choice(digits)
                    if roll_dice(WORD_NUMBER_SUFFIX_CHANCE)
                    else ""
                )
            )
            if roll_dice(WORD_NUMBER_SUFFIX_CHANCE)
            else ""
        )
        return random_word() + suffix

    objects = []
    for _ in range(NUM_OBJECTS):

        # Generate name
        name_words = []
        for _ in range(random_int(OBJECT_NAME_WORD_COUNT_RANGE)):
            if roll_dice(COMPOSITE_WORD_CHANCE):
                # Will be a word-like-this
                word = "-".join(
                    random_object_word()
                    for _ in range(random_int(OBJECT_NAME_WORD_COUNT_RANGE))
                )
            else:
                word = random_object_word().title()
            name_words.append(word)
        name = " ".join(name_words)

        network_system = random.choice(network_systems)

        objects.append(
            Object(
                name=name,
                object_id=random_id(),
                url=format_url(network_system, name),
                type=random.choice(object_types),
                network_system=network_system,
            )
        )

    return set_pks(objects) 
Example 76
Project: TESTGIT   Author: B-ROY   File: detail.py    Apache License 2.0 4 votes vote down vote up
def get_template_names(self):
        """
        Return a list of template names to be used for the request. May not be
        called if render_to_response is overridden. Returns the following list:

        * the value of ``template_name`` on the view (if provided)
        * the contents of the ``template_name_field`` field on the
          object instance that the view is operating upon (if available)
        * ``<app_label>/<object_name><template_name_suffix>.html``
        """
        try:
            names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
        except ImproperlyConfigured:
            # If template_name isn't specified, it's not a problem --
            # we just start with an empty list.
            names = []

            # If self.template_name_field is set, grab the value of the field
            # of that name from the object; this is the most specific template
            # name, if given.
            if self.object and self.template_name_field:
                name = getattr(self.object, self.template_name_field, None)
                if name:
                    names.insert(0, name)

            # The least-specific option is the default <app>/<model>_detail.html;
            # only use this if the object in question is a model.
            if isinstance(self.object, models.Model):
                names.append("%s/%s%s.html" % (
                    self.object._meta.app_label,
                    self.object._meta.model_name,
                    self.template_name_suffix
                ))
            elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
                names.append("%s/%s%s.html" % (
                    self.model._meta.app_label,
                    self.model._meta.model_name,
                    self.template_name_suffix
                ))

            # If we still haven't managed to find any template names, we should
            # re-raise the ImproperlyConfigured to alert the user.
            if not names:
                raise

        return names 
Example 77
Project: TESTGIT   Author: B-ROY   File: related.py    Apache License 2.0 4 votes vote down vote up
def add_lazy_relation(cls, field, relation, operation):
    """
    Adds a lookup on ``cls`` when a related field is defined using a string,
    i.e.::

        class MyModel(Model):
            fk = ForeignKey("AnotherModel")

    This string can be:

        * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
          relation.

        * The name of a model (i.e "AnotherModel") to indicate another model in
          the same app.

        * An app-label and model name (i.e. "someapp.AnotherModel") to indicate
          another model in a different app.

    If the other model hasn't yet been loaded -- almost a given if you're using
    lazy relationships -- then the relation won't be set up until the
    class_prepared signal fires at the end of model initialization.

    operation is the work that must be performed once the relation can be resolved.
    """
    # Check for recursive relations
    if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
        app_label = cls._meta.app_label
        model_name = cls.__name__

    else:
        # Look for an "app.Model" relation

        if isinstance(relation, six.string_types):
            try:
                app_label, model_name = relation.split(".")
            except ValueError:
                # If we can't split, assume a model in current app
                app_label = cls._meta.app_label
                model_name = relation
        else:
            # it's actually a model class
            app_label = relation._meta.app_label
            model_name = relation._meta.object_name

    # Try to look up the related model, and if it's already loaded resolve the
    # string right away. If get_model returns None, it means that the related
    # model isn't loaded yet, so we need to pend the relation until the class
    # is prepared.
    model = get_model(app_label, model_name,
                      seed_cache=False, only_installed=False)
    if model:
        operation(field, model, cls)
    else:
        key = (app_label, model_name)
        value = (cls, field, operation)
        pending_lookups.setdefault(key, []).append(value) 
Example 78
Project: TESTGIT   Author: B-ROY   File: related.py    Apache License 2.0 4 votes vote down vote up
def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookup_type,
                              raw_value):
        from django.db.models.sql.where import SubqueryConstraint, Constraint, AND, OR
        root_constraint = constraint_class()
        assert len(targets) == len(sources)

        def get_normalized_value(value):

            from django.db.models import Model
            if isinstance(value, Model):
                value_list = []
                for source in sources:
                    # Account for one-to-one relations when sent a different model
                    while not isinstance(value, source.model) and source.rel:
                        source = source.rel.to._meta.get_field(source.rel.field_name)
                    value_list.append(getattr(value, source.attname))
                return tuple(value_list)
            elif not isinstance(value, tuple):
                return (value,)
            return value

        is_multicolumn = len(self.related_fields) > 1
        if (hasattr(raw_value, '_as_sql') or
                hasattr(raw_value, 'get_compiler')):
            root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
                                                   [source.name for source in sources], raw_value),
                                AND)
        elif lookup_type == 'isnull':
            root_constraint.add(
                (Constraint(alias, targets[0].column, targets[0]), lookup_type, raw_value), AND)
        elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
                                         and not is_multicolumn)):
            value = get_normalized_value(raw_value)
            for index, source in enumerate(sources):
                root_constraint.add(
                    (Constraint(alias, targets[index].column, sources[index]), lookup_type,
                     value[index]), AND)
        elif lookup_type in ['range', 'in'] and not is_multicolumn:
            values = [get_normalized_value(value) for value in raw_value]
            value = [val[0] for val in values]
            root_constraint.add(
                (Constraint(alias, targets[0].column, sources[0]), lookup_type, value), AND)
        elif lookup_type == 'in':
            values = [get_normalized_value(value) for value in raw_value]
            for value in values:
                value_constraint = constraint_class()
                for index, target in enumerate(targets):
                    value_constraint.add(
                        (Constraint(alias, target.column, sources[index]), 'exact', value[index]),
                        AND)
                root_constraint.add(value_constraint, OR)
        else:
            raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
        return root_constraint 
Example 79
Project: TESTGIT   Author: B-ROY   File: related.py    Apache License 2.0 4 votes vote down vote up
def create_many_to_many_intermediary_model(field, klass):
    from django.db import models
    managed = True
    if isinstance(field.rel.to, six.string_types) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT:
        to_model = field.rel.to
        to = to_model.split('.')[-1]

        def set_managed(field, model, cls):
            field.rel.through._meta.managed = model._meta.managed or cls._meta.managed
        add_lazy_relation(klass, field, to_model, set_managed)
    elif isinstance(field.rel.to, six.string_types):
        to = klass._meta.object_name
        to_model = klass
        managed = klass._meta.managed
    else:
        to = field.rel.to._meta.object_name
        to_model = field.rel.to
        managed = klass._meta.managed or to_model._meta.managed
    name = '%s_%s' % (klass._meta.object_name, field.name)
    if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name:
        from_ = 'from_%s' % to.lower()
        to = 'to_%s' % to.lower()
    else:
        from_ = klass._meta.model_name
        to = to.lower()
    meta = type('Meta', (object,), {
        'db_table': field._get_m2m_db_table(klass._meta),
        'managed': managed,
        'auto_created': klass,
        'app_label': klass._meta.app_label,
        'db_tablespace': klass._meta.db_tablespace,
        'unique_together': (from_, to),
        'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
        'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
    })
    # Construct and return the new class.
    return type(str(name), (models.Model,), {
        'Meta': meta,
        '__module__': klass.__module__,
        from_: models.ForeignKey(klass, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.rel.db_constraint),
        to: models.ForeignKey(to_model, related_name='%s+' % name, db_tablespace=field.db_tablespace, db_constraint=field.rel.db_constraint)
    }) 
Example 80
Project: AneMo   Author: jspargo   File: detail.py    GNU General Public License v2.0 4 votes vote down vote up
def get_template_names(self):
        """
        Return a list of template names to be used for the request. May not be
        called if render_to_response is overridden. Returns the following list:

        * the value of ``template_name`` on the view (if provided)
        * the contents of the ``template_name_field`` field on the
          object instance that the view is operating upon (if available)
        * ``<app_label>/<model_name><template_name_suffix>.html``
        """
        try:
            names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
        except ImproperlyConfigured:
            # If template_name isn't specified, it's not a problem --
            # we just start with an empty list.
            names = []

            # If self.template_name_field is set, grab the value of the field
            # of that name from the object; this is the most specific template
            # name, if given.
            if self.object and self.template_name_field:
                name = getattr(self.object, self.template_name_field, None)
                if name:
                    names.insert(0, name)

            # The least-specific option is the default <app>/<model>_detail.html;
            # only use this if the object in question is a model.
            if isinstance(self.object, models.Model):
                names.append("%s/%s%s.html" % (
                    self.object._meta.app_label,
                    self.object._meta.model_name,
                    self.template_name_suffix
                ))
            elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
                names.append("%s/%s%s.html" % (
                    self.model._meta.app_label,
                    self.model._meta.model_name,
                    self.template_name_suffix
                ))

            # If we still haven't managed to find any template names, we should
            # re-raise the ImproperlyConfigured to alert the user.
            if not names:
                raise

        return names