Python django.db.models.ForeignKey() Examples

The following are 30 code examples of django.db.models.ForeignKey(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: layermapping.py    From GTDWeb with GNU General Public License v2.0 7 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        this routine will retrieve the related model for the ForeignKey
        mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example #2
Source File: validation.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def validate_prepopulated_fields(self, cls, model):
        " Validate that prepopulated_fields if a dictionary  containing allowed field types. "
        # prepopulated_fields
        if hasattr(cls, 'prepopulated_fields'):
            check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
            for field, val in cls.prepopulated_fields.items():
                f = get_field(cls, model, 'prepopulated_fields', field)
                if isinstance(f, (models.DateTimeField, models.ForeignKey,
                        models.ManyToManyField)):
                    raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
                            "is either a DateTimeField, ForeignKey or "
                            "ManyToManyField. This isn't allowed."
                            % (cls.__name__, field))
                check_isseq(cls, "prepopulated_fields['%s']" % field, val)
                for idx, f in enumerate(val):
                    get_field(cls, model, "prepopulated_fields['%s'][%d]" % (field, idx), f) 
Example #3
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(ForeignKey, self).deconstruct()
        del kwargs['to_fields']
        del kwargs['from_fields']
        # Handle the simpler arguments
        if self.db_index:
            del kwargs['db_index']
        else:
            kwargs['db_index'] = False
        if self.db_constraint is not True:
            kwargs['db_constraint'] = self.db_constraint
        # Rel needs more work.
        to_meta = getattr(self.rel.to, "_meta", None)
        if self.rel.field_name and (not to_meta or (to_meta.pk and self.rel.field_name != to_meta.pk.name)):
            kwargs['to_field'] = self.rel.field_name
        return name, path, args, kwargs 
Example #4
Source File: 0002_auto__add_project__add_unique_project_name_organization.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def forwards(self, orm):
        # Adding model 'Project'
        db.create_table('api_project', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('organization', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_organization', to=orm['auth.User'])),
            ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_creator', to=orm['auth.User'])),
            ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
        ))
        db.send_create_signal('api', ['Project'])

        # Adding unique constraint on 'Project', fields ['name', 'organization']
        db.create_unique('api_project', ['name', 'organization_id'])

        # Adding M2M table for field projects on 'Team'
        db.create_table('api_team_projects', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('team', models.ForeignKey(orm['api.team'], null=False)),
            ('project', models.ForeignKey(orm['api.project'], null=False))
        ))
        db.create_unique('api_team_projects', ['team_id', 'project_id']) 
Example #5
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def validate(self, value, model_instance):
        if self.rel.parent_link:
            return
        super(ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        using = router.db_for_read(model_instance.__class__, instance=model_instance)
        qs = self.rel.to._default_manager.using(using).filter(
            **{self.rel.field_name: value}
        )
        qs = qs.complex_filter(self.get_limit_choices_to())
        if not qs.exists():
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={
                    'model': self.rel.to._meta.verbose_name, 'pk': value,
                    'field': self.rel.field_name, 'value': value,
                },  # 'pk' is included for backwards compatibility
            ) 
Example #6
Source File: decorator.py    From FIR with GNU General Public License v3.0 6 votes vote down vote up
def has_perm(self, user, permission):
    if user.is_superuser:
        return True
    if isinstance(permission, six.string_types):
        permission = [permission, ]
    if user.has_perms(permission):
        return True
    if self._authorization_meta.owner_field and self._authorization_meta.owner_permission and \
       self._authorization_meta.owner_permission in permission and \
       user.pk == getattr(self, self._authorization_meta.owner_field).pk:
        return True
    paths = self._authorization_meta.model.get_authorization_paths(user, permission)
    if not paths.count():
        return False
    for field in self._authorization_meta.fields:
        f = self._meta.get_field(field)
        relation = getattr(self, field)
        if isinstance(f, models.ManyToManyField):
            qs_filter = reduce(lambda x, y: x | y, [Q(path__startswith=path) for path in paths])
            if relation.filter(qs_filter).distinct().exists():
                return True
        elif isinstance(f, models.ForeignKey):
            if relation is not None and any(relation.path.startswith(p) for p in paths):
                return True
    return False 
Example #7
Source File: checks.py    From bioforum with MIT License 6 votes vote down vote up
def _check_raw_id_fields_item(self, obj, model, field_name, label):
        """ Check an item of `raw_id_fields`, i.e. check that field named
        `field_name` exists in model `model` and is a ForeignKey or a
        ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E002')
        else:
            if not field.many_to_many and not isinstance(field, models.ForeignKey):
                return must_be('a foreign key or a many-to-many field',
                               option=label, obj=obj, id='admin.E003')
            else:
                return [] 
Example #8
Source File: checks.py    From bioforum with MIT License 6 votes vote down vote up
def _check_radio_fields_key(self, obj, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        obj=obj.__class__,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
Example #9
Source File: options.py    From bioforum with MIT License 6 votes vote down vote up
def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """
        Get a form Field for a ForeignKey.
        """
        db = kwargs.get('using')

        if db_field.name in self.get_autocomplete_fields(request):
            kwargs['widget'] = AutocompleteSelect(db_field.remote_field, self.admin_site, using=db)
        elif db_field.name in self.raw_id_fields:
            kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=db)
        elif db_field.name in self.radio_fields:
            kwargs['widget'] = widgets.AdminRadioSelect(attrs={
                'class': get_ul_class(self.radio_fields[db_field.name]),
            })
            kwargs['empty_label'] = _('None') if db_field.blank else None

        if 'queryset' not in kwargs:
            queryset = self.get_field_queryset(db, db_field, request)
            if queryset is not None:
                kwargs['queryset'] = queryset

        return db_field.formfield(**kwargs) 
Example #10
Source File: utils.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def allow_search_fields(cls, exclude=None):
    opts = cls._meta
    if not exclude:
        exclude = ['onidc', 'slug', 'created', 'modified']
    exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
    fields = []
    for f in opts.fields:
        if exclude and f.name in exclude:
            continue
        if isinstance(f, models.ForeignKey):
            submodel = f.related_model
            for sub in submodel._meta.fields:
                if exclude and sub.name in exclude:
                    continue
                if isinstance(sub, models.CharField) \
                        and not getattr(sub, 'choices'):
                    fields.append(f.name + '__' + sub.name + '__icontains')
        if isinstance(f, models.CharField):
            fields.append(f.name + '__icontains')
    return fields 
Example #11
Source File: layermapping.py    From bioforum with MIT License 6 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        retrieve the related model for the ForeignKey mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example #12
Source File: docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def _get_field_type(field):
    if isinstance(field, models.ForeignKey):
        if django.VERSION >= (2, 0):
            to = field.remote_field.model
            if isinstance(to, str):
                to = _resolve_model(field, to)
        else:
            to = field.rel.to
            if isinstance(to, str):
                to = _resolve_model(field, to)

        return u":type %s: %s to :class:`~%s.%s`" % (
            field.name,
            type(field).__name__,
            to.__module__,
            to.__name__,
        )
    else:
        return u":type %s: %s" % (field.name, type(field).__name__) 
Example #13
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_raw_id_fields_item(self, cls, model, field_name, label):
        """ Check an item of `raw_id_fields`, i.e. check that field named
        `field_name` exists in model `model` and is a ForeignKey or a
        ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E002')
        else:
            if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
                return must_be('a ForeignKey or ManyToManyField',
                               option=label, obj=cls, id='admin.E003')
            else:
                return [] 
Example #14
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def test_model_init_params(self):
        """Model __init__ gets all fields as params."""
        lines = []
        docstrings._add_model_fields_as_params(self.app, SimpleModel, lines)
        self.assertEqual(
            lines,
            [
                ":param id: Id",
                ":type id: AutoField",
                ":param user: User",
                ":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param user2: User2",
                ":type user2: ForeignKey to"
                " :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
                ":param user3: User3",
                ":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param dummy_field: Dummy field",
                ":type dummy_field: CharField",
            ],
        ) 
Example #15
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_radio_fields_key(self, cls, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
Example #16
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def generic_inlineformset_factory(model, form=ModelForm,
                                  formset=BaseGenericInlineFormSet,
                                  ct_field="content_type", fk_field="object_id",
                                  fields=None, exclude=None,
                                  extra=3, can_order=False, can_delete=True,
                                  max_num=None, formfield_callback=None,
                                  validate_max=False, for_concrete_model=True,
                                  min_num=None, validate_min=False):
    """
    Returns a ``GenericInlineFormSet`` for the given kwargs.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults ``content_type`` and ``object_id`` respectively.
    """
    opts = model._meta
    # if there is no field called `ct_field` let the exception propagate
    ct_field = opts.get_field(ct_field)
    if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType:
        raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field)
    fk_field = opts.get_field(fk_field)  # let the exception propagate
    if exclude is not None:
        exclude = list(exclude)
        exclude.extend([ct_field.name, fk_field.name])
    else:
        exclude = [ct_field.name, fk_field.name]
    FormSet = modelformset_factory(model, form=form,
                                   formfield_callback=formfield_callback,
                                   formset=formset,
                                   extra=extra, can_delete=can_delete, can_order=can_order,
                                   fields=fields, exclude=exclude, max_num=max_num,
                                   validate_max=validate_max, min_num=min_num,
                                   validate_min=validate_min)
    FormSet.ct_field = ct_field
    FormSet.ct_fk_field = fk_field
    FormSet.for_concrete_model = for_concrete_model
    return FormSet 
Example #17
Source File: 0008_auto_add_user_star_field_to_project.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def forwards(self, orm):
        # Adding M2M table for field user_stars on 'Project'
        m2m_table_name = db.shorten_name(u'api_project_user_stars')
        db.create_table(m2m_table_name, (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('project', models.ForeignKey(orm['api.project'], null=False)),
            ('user', models.ForeignKey(orm[u'auth.user'], null=False))
        ))
        db.create_unique(m2m_table_name, ['project_id', 'user_id']) 
Example #18
Source File: edit.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def get_field_style(self, db_field, style, **kwargs):
        if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
            attrs = {'widget': widgets.AdminRadioSelect(
                attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
            if db_field.choices:
                attrs['choices'] = db_field.get_choices(
                    include_blank=db_field.blank,
                    blank_choice=[('', _('Null'))]
                )
            return attrs

        if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
            return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
                    'help_text': None} 
Example #19
Source File: creation.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def sql_for_inline_many_to_many_references(self, model, field, style):
        opts = model._meta
        qn = self.connection.ops.quote_name

        columndef = '    {column} {type} {options},'
        table_output = [
            columndef.format(
                column=style.SQL_FIELD(qn(field.m2m_column_name())),
                type=style.SQL_COLTYPE(models.ForeignKey(model).db_type(
                    connection=self.connection)),
                options=style.SQL_KEYWORD('NOT NULL')
            ),
            columndef.format(
                column=style.SQL_FIELD(qn(field.m2m_reverse_name())),
                type=style.SQL_COLTYPE(models.ForeignKey(field.rel.to).db_type(
                    connection=self.connection)),
                options=style.SQL_KEYWORD('NOT NULL')
            ),
        ]

        deferred = [
            (field.m2m_db_table(), field.m2m_column_name(), opts.db_table,
                opts.pk.column),
            (field.m2m_db_table(), field.m2m_reverse_name(),
                field.rel.to._meta.db_table, field.rel.to._meta.pk.column)
        ]
        return table_output, deferred 
Example #20
Source File: utils.py    From meeting with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, to, on_delete=models.DO_NOTHING, related_name=None, related_query_name=None,
                 limit_choices_to=None, parent_link=False, to_field=None, db_constraint=False,  **kwargs):
        super(ForeignKey, self).__init__(to, on_delete, related_name, related_query_name, limit_choices_to,
                                         parent_link, to_field, db_constraint, **kwargs) 
Example #21
Source File: snapshots.py    From Politikon with GNU General Public License v2.0 5 votes vote down vote up
def create_snapshot_model(cls, fields=[]):
    """ Dynamically create a main Model, 1-1 with the model being snapshotted. """
    # Models must have unique names, so we create a name by suffixing model class name with 'Snapshot'
    name = cls.__name__ + 'Snapshot'

    class Meta:
        db_table = '%s_snapshot' % cls._meta.db_table
        app_label = cls._meta.app_label
        verbose_name = u'%s - snapshot' % cls._meta.verbose_name
        verbose_name_plural = u'%s - snapshoty' % cls._meta.verbose_name
        ordering = ['-created_at']

    # Set up a dictionary to simulate declarations within a class.
    attrs = {
        '__module__': cls.__module__,
        'Meta': Meta,
        'id': models.AutoField(primary_key=True),
        'created_at': models.DateTimeField(u"stworzony dnia", auto_now_add=True),
        'snapshot_of': models.ForeignKey(cls, verbose_name=u"dotyczy", null=False, on_delete=models.PROTECT, related_name="snapshots"),
        '__unicode__': lambda self: u'snapshot',
    }

    # Copy fields
    for field_name in fields:
        target_field = cls._meta.get_field_by_name(field_name)[0]
        attrs[field_name] = copy_field(target_field)

    return type(name, (models.Model,), attrs) 
Example #22
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 5 votes vote down vote up
def test_foreignkey_type(self):
        """Test how the foreignkeys are rendered."""
        self.assertEqual(
            docstrings._get_field_type(SimpleModel._meta.get_field("user")),
            ":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
        )
        self.assertEqual(
            docstrings._get_field_type(SimpleModel._meta.get_field("user2")),
            ":type user2: ForeignKey to"
            " :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
        )
        self.assertEqual(
            docstrings._get_field_type(SimpleModel._meta.get_field("user3")),
            ":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
        ) 
Example #23
Source File: test_Serializer.py    From django-simple-serializer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        self.time_func = TimeFormatFactory.get_time_func('string')
        # DATABASES = {
        #     'default': {
        #     'ENGINE': 'django.db.backends.sqlite3',
        #     'NAME': ':memory:',
        #     'USER': '',                      # Not used with sqlite3.
        #     'PASSWORD': '',                  # Not used with sqlite3.
        #     'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        #     'PORT': '',
        #     }
        # }
        # settings.configure(DATABASES=DATABASES, DEBUG=True)
        # class TestAuthor(models.Model):
        #     name = models.CharField(default='test_author')
        #
        #     def __unicode__(self):
        #         return self.name
        #
        # class TestTags(models.Model):
        #     tag = models.CharField(default='test_tag')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        # class TestArticle(models.Model):
        #     title = models.CharField(default='test')
        #     content = models.CharField(default='test')
        #     author = models.ForeignKey(TestAuthor, related_name='author_art')
        #     tags = models.ManyToManyField(TestTags, related_name='tag_art')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        #
        # self.author = TestAuthor()
        # self.author.save()
        # tags = TestTags(tag='tag1')
        # tags.save()
        # self.article = TestArticle(author=self.author)
        # self.article.tags.add(tags)
        # self.article.save() 
Example #24
Source File: related.py    From bioforum with MIT License 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        kwargs['on_delete'] = self.remote_field.on_delete
        kwargs['from_fields'] = self.from_fields
        kwargs['to_fields'] = self.to_fields

        if self.remote_field.parent_link:
            kwargs['parent_link'] = self.remote_field.parent_link
        # Work out string form of "to"
        if isinstance(self.remote_field.model, str):
            kwargs['to'] = self.remote_field.model
        else:
            kwargs['to'] = "%s.%s" % (
                self.remote_field.model._meta.app_label,
                self.remote_field.model._meta.object_name,
            )
        # If swappable is True, then see if we're actually pointing to the target
        # of a swap.
        swappable_setting = self.swappable_setting
        if swappable_setting is not None:
            # If it's already a settings reference, error
            if hasattr(kwargs['to'], "setting_name"):
                if kwargs['to'].setting_name != swappable_setting:
                    raise ValueError(
                        "Cannot deconstruct a ForeignKey pointing to a model "
                        "that is swapped in place of more than one model (%s and %s)"
                        % (kwargs['to'].setting_name, swappable_setting)
                    )
            # Set it
            from django.db.migrations.writer import SettingsReference
            kwargs['to'] = SettingsReference(
                kwargs['to'],
                swappable_setting,
            )
        return name, path, args, kwargs 
Example #25
Source File: validation.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def validate_fk_name(self, cls, model):
        " Validate that fk_name refers to a ForeignKey. "
        if cls.fk_name:  # default value is None
            f = get_field(cls, model, 'fk_name', cls.fk_name)
            if not isinstance(f, models.ForeignKey):
                raise ImproperlyConfigured("'%s.fk_name is not an instance of "
                        "models.ForeignKey." % cls.__name__) 
Example #26
Source File: test_encrypted.py    From django-cryptography with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_base_fields(self):
        class Related(models.Model):
            field = encrypt(
                models.ForeignKey('fields.EncryptedIntegerModel',
                                  models.CASCADE))

            class Meta:
                app_label = 'myapp'

        obj = Related()
        errors = obj.check()
        self.assertEqual(1, len(errors))
        self.assertEqual('encrypted.E002', errors[0].id) 
Example #27
Source File: decorator.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def tree_authorization(fields=None, tree_model='incidents.BusinessLine', owner_field=None, owner_permission=None):
    def set_meta(cls):
        if not hasattr(cls, '_authorization_meta'):
            class AuthorizationMeta:
                owner_field = None
                owner_permission = None
                fields = ('business_lines',)
                tree_model = None

                @property
                def model(self):
                    if isinstance(self.tree_model, six.string_types):
                        self.tree_model = apps.get_model(*self.tree_model.split('.'))
                    return self.tree_model

            AuthorizationMeta.tree_model = tree_model
            cls._authorization_meta = AuthorizationMeta()
        if fields is not None:
            if isinstance(fields, (tuple, list)):
                cls._authorization_meta.fields = fields
            elif isinstance(fields, six.string_types):
                cls._authorization_meta.fields = (fields,)
            else:
                raise Exception("Linking field unrecognized")
        for field in cls._authorization_meta.fields:
            f = cls._meta.get_field(field)
            if not isinstance(f, (models.ForeignKey, models.ManyToManyField)):
                raise Exception("Linking field not a link")
        if isinstance(owner_permission, six.string_types) and isinstance(owner_field, six.string_types):
            f = cls._meta.get_field(owner_field)
            if isinstance(f, models.ForeignKey):
                cls._authorization_meta.owner_permission = owner_permission
                cls._authorization_meta.owner_field = owner_field
        cls.get_authorization_filter = classmethod(get_authorization_filter)
        cls.add_to_class('has_perm', has_perm)
        cls.has_model_perm = classmethod(has_model_perm)
        AuthorizationManager().contribute_to_class(cls, 'authorization')
        return cls

    return set_meta 
Example #28
Source File: seeder.py    From django-seed with MIT License 5 votes vote down vote up
def guess_field_formatters(self, faker):
        """
        Gets the formatter methods for each field using the guessers
        or related object fields
        :param faker: Faker factory object
        """
        formatters = {}
        name_guesser = NameGuesser(faker)
        field_type_guesser = FieldTypeGuesser(faker)

        for field in self.model._meta.fields:

            field_name = field.name

            if field.primary_key:
                continue

            if field.get_default():
                formatters[field_name] = field.get_default()
                continue

            if isinstance(field, (ForeignKey, ManyToManyField, OneToOneField)):
                formatters[field_name] = self.build_relation(field, field.related_model)
                continue

            if not field.choices:
                formatter = name_guesser.guess_format(field_name)
                if formatter:
                    formatters[field_name] = formatter
                    continue

            formatter = field_type_guesser.guess_format(field)
            if formatter:
                formatters[field_name] = formatter
                continue

        return formatters 
Example #29
Source File: managers.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_field_name(self):
        field_name = self._get_field_name()
        try:
            field = self.model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return [
                checks.Error(
                    "CurrentSiteManager could not find a field named '%s'." % field_name,
                    hint=None,
                    obj=self,
                    id='sites.E001',
                )
            ]

        if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
            return [
                checks.Error(
                    "CurrentSiteManager cannot use '%s.%s' as it is not a ForeignKey or ManyToManyField." % (
                        self.model._meta.object_name, field_name
                    ),
                    hint=None,
                    obj=self,
                    id='sites.E002',
                )
            ]

        return [] 
Example #30
Source File: model.py    From dingtalk-django-example with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, to, on_delete=models.DO_NOTHING, related_name=None, related_query_name=None,
                 limit_choices_to=None, parent_link=False, to_field=None, db_constraint=False,  **kwargs):
        super(ForeignKey, self).__init__(to, on_delete, related_name, related_query_name, limit_choices_to,
                                         parent_link, to_field, db_constraint, **kwargs)