django.core.exceptions.FieldError - python examples

Here are the examples of the python api django.core.exceptions.FieldError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

34 Examples 7

3 View Complete Implementation : subqueries.py
Copyright GNU General Public License v2.0
Author : blackye
    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field, model, direct, m2m = self.model._meta.get_field_by_name(name)
            if not direct or m2m:
                raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
            if model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)

3 View Complete Implementation : aggregates.py
Copyright MIT License
Author : bpgc-cte
    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        # Aggregates are not allowed in UPDATE queries, so ignore for_save
        c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
        if not summarize:
            expressions = c.get_source_expressions()
            for index, expr in enumerate(expressions):
                if expr.contains_aggregate:
                    before_resolved = self.get_source_expressions()[index]
                    name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved)
                    raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
        return c

3 View Complete Implementation : expressions.py
Copyright MIT License
Author : bpgc-cte
    @cached_property
    def output_field(self):
        """
        Returns the output type of this expressions.
        """
        if self._output_field_or_none is None:
            raise FieldError("Cannot resolve expression type, unknown output_field")
        return self._output_field_or_none

3 View Complete Implementation : reverse_related.py
Copyright MIT License
Author : bpgc-cte
    @property
    def target_field(self):
        """
        When filtering against this relation, returns the field on the remote
        model against which the filtering should happen.
        """
        target_fields = self.get_path_info()[-1].target_fields
        if len(target_fields) > 1:
            raise exceptions.FieldError("Can't use target_field for multicolumn relations.")
        return target_fields[0]

3 View Complete Implementation : aggregates.py
Copyright Apache License 2.0
Author : drexly
    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        # Aggregates are not allowed in UPDATE queries, so ignore for_save
        c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
        if not summarize:
            expressions = c.get_source_expressions()
            for index, expr in enumerate(expressions):
                if expr.contains_aggregate:
                    before_resolved = self.get_source_expressions()[index]
                    name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved)
                    raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
        c._patch_aggregate(query)  # backward-compatibility support
        return c

3 View Complete Implementation : subqueries.py
Copyright Apache License 2.0
Author : edisonlz
    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field, model, direct, m2m = self.get_meta().get_field_by_name(name)
            if not direct or m2m:
                raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
            if model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)

3 View Complete Implementation : aggregates.py
Copyright MIT License
Author : rizwansoaib
    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        # Aggregates are not allowed in UPDATE queries, so ignore for_save
        c = super().resolve_expression(query, allow_joins, reuse, summarize)
        c.filter = c.filter and c.filter.resolve_expression(query, allow_joins, reuse, summarize)
        if not summarize:
            # Call Aggregate.get_source_expressions() to avoid
            # returning self.filter and including that in this loop.
            expressions = super(Aggregate, c).get_source_expressions()
            for index, expr in enumerate(expressions):
                if expr.contains_aggregate:
                    before_resolved = self.get_source_expressions()[index]
                    name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved)
                    raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
        return c

3 View Complete Implementation : expressions.py
Copyright MIT License
Author : rizwansoaib
    @cached_property
    def output_field(self):
        """Return the output type of this expressions."""
        output_field = self._resolve_output_field()
        if output_field is None:
            self._output_field_resolved_to_none = True
            raise FieldError('Cannot resolve expression type, unknown output_field')
        return output_field

3 View Complete Implementation : expressions.py
Copyright MIT License
Author : rizwansoaib
    def _resolve_output_field(self):
        """
        Attempt to infer the output type of the expression. If the output
        fields of all source fields match then, simply infer the same type
        here. This isn't always correct, but it makes sense most of the time.

        Consider the difference between `2 + 2` and `2 / 3`. Inferring
        the type here is a convenience for the common case. The user should
        supply their own output_field with more complex computations.

        If a source's output field resolves to None, exclude it from this check.
        If all sources are None, then an error is raised higher up the stack in
        the output_field property.
        """
        sources_iter = (source for source in self.get_source_fields() if source is not None)
        for output_field in sources_iter:
            if any(not isinstance(output_field, source.__clast__) for source in sources_iter):
                raise FieldError('Expression contains mixed types. You must set output_field.')
            return output_field

3 View Complete Implementation : reverse_related.py
Copyright MIT License
Author : rizwansoaib
    @property
    def target_field(self):
        """
        When filtering against this relation, return the field on the remote
        model against which the filtering should happen.
        """
        target_fields = self.get_path_info()[-1].target_fields
        if len(target_fields) > 1:
            raise exceptions.FieldError("Can't use target_field for multicolumn relations.")
        return target_fields[0]

3 View Complete Implementation : models.py
Copyright GNU General Public License v3.0
Author : safwanrahman
    def save(self, *args, **kwargs):
        # Check whether user or the group field is present
        # At least one field should be present there
        # Through from the functionality its not possible, just in case! ;)
        if self.user or self.group:
            super(PushInformation, self).save(*args, **kwargs)
        else:
            raise FieldError('At least user or group should be present')

3 View Complete Implementation : utils.py
Copyright MIT License
Author : stphivos
def validate_field(field_name, model_fields, for_update=False):
    if '__' in field_name and for_update:
        raise FieldError(
            'Cannot update model field %r (only non-relations and foreign keys permitted).' % field_name
        )
    if field_name != 'pk' and field_name not in model_fields:
        message = "Cannot resolve keyword '{}' into field. Choices are {}.".format(
            field_name,
            ', '.join(map(repr, map(str, sorted(model_fields))))
        )
        raise FieldError(message)

0 View Complete Implementation : utils.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
def _get_dissected_lookup(model, lookup):
    """Return the dissected info of a lookup."""
    dissected = {
        'relation': [],
        'field': '',
        'supplement': '',
        'translatable': False,
    }

    def _fill_dissected(model, *relation_parts):
        root = relation_parts[0]
        nest = relation_parts[1:]

        try:
            if root == 'pk':
                field = model._meta.pk
            else:
                field = model._meta.get_field(root)
        except Exception as e:
            if not dissected['relation'] or nest or dissected['field']:
                raise e
            dissected['supplement'] = root
        else:
            field_model = field.related_model
            if field_model:
                dissected['relation'].append(root)
                if nest:
                    _fill_dissected(field_model, *nest)
            else:
                dissected['field'] = root
                if issubclast(model, translations.models.Translatable):
                    if root in model._get_translatable_fields_names():
                        dissected['translatable'] = True
                if nest:
                    if len(nest) == 1:
                        dissected['supplement'] = nest[0]
                    else:
                        raise FieldError("Unsupported lookup '{}'".format(
                            nest[0])
                        )

    parts = lookup.split(LOOKUP_SEP)

    _fill_dissected(model, *parts)

    return dissected

0 View Complete Implementation : edit.py
Copyright Apache License 2.0
Author : BeanWei
    @filter_hook
    def get_model_form(self, **kwargs):
        """
        Returns a Form clast for use in the admin add view. This is used by
        add_view and change_view.
        """
        if self.exclude is None:
            exclude = []
        else:
            exclude = list(self.exclude)
        exclude.extend(self.get_readonly_fields())
        if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            # Take the custom ModelForm's Meta.exclude into account only if the
            # ModelAdmin doesn't define its own.
            exclude.extend(self.form._meta.exclude)
        # if exclude is an empty list we past None to be consistant with the
        # default on modelform_factory
        exclude = exclude or None
        defaults = {
            "form": self.form,
            "fields": self.fields and list(self.fields) or None,
            "exclude": exclude,
            "formfield_callback": self.formfield_for_dbfield,
        }
        defaults.update(kwargs)

        if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
            defaults['fields'] = forms.ALL_FIELDS

        return modelform_factory(self.model, **defaults)

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of clast %s.'
                             % (e, self.__clast__.__name__))

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def __new__(cls, name, bases, attrs):
        super_new = super(ModelBase, cls).__new__

        # six.with_metaclast() inserts an extra clast called 'NewBase' in the
        # inheritance tree: Model -> NewBase -> object. But the initialization
        # should be executed only once for a given model clast.

        # attrs will never be empty for clastes declared in the standard way
        # (ie. with the `clast` keyword). This is quite robust.
        if name == 'NewBase' and attrs == {}:
            return super_new(cls, name, bases, attrs)

        # Also ensure initialization is only performed for subclastes of Model
        # (excluding Model clast itself).
        parents = [b for b in bases if isinstance(b, ModelBase) and
                not (b.__name__ == 'NewBase' and b.__mro__ == (b, object))]
        if not parents:
            return super_new(cls, name, bases, attrs)

        # Create the clast.
        module = attrs.pop('__module__')
        new_clast = super_new(cls, name, bases, {'__module__': module})
        attr_meta = attrs.pop('Meta', None)
        abstract = getattr(attr_meta, 'abstract', False)
        if not attr_meta:
            meta = getattr(new_clast, 'Meta', None)
        else:
            meta = attr_meta
        base_meta = getattr(new_clast, '_meta', None)

        if getattr(meta, 'app_label', None) is None:
            # Figure out the app_label by looking one level up.
            # For 'django.contrib.sites.models', this would be 'sites'.
            model_module = sys.modules[new_clast.__module__]
            kwargs = {"app_label": model_module.__name__.split('.')[-2]}
        else:
            kwargs = {}

        new_clast.add_to_clast('_meta', Options(meta, **kwargs))
        if not abstract:
            new_clast.add_to_clast('DoesNotExist', subclast_exception(str('DoesNotExist'),
                    tuple(x.DoesNotExist
                          for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
                    or (ObjectDoesNotExist,),
                    module, attached_to=new_clast))
            new_clast.add_to_clast('MultipleObjectsReturned', subclast_exception(str('MultipleObjectsReturned'),
                    tuple(x.MultipleObjectsReturned
                          for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
                    or (MultipleObjectsReturned,),
                    module, attached_to=new_clast))
            if base_meta and not base_meta.abstract:
                # Non-abstract child clastes inherit some attributes from their
                # non-abstract parent (unless an ABC comes before it in the
                # method resolution order).
                if not hasattr(meta, 'ordering'):
                    new_clast._meta.ordering = base_meta.ordering
                if not hasattr(meta, 'get_latest_by'):
                    new_clast._meta.get_latest_by = base_meta.get_latest_by

        is_proxy = new_clast._meta.proxy

        # If the model is a proxy, ensure that the base clast
        # hasn't been swapped out.
        if is_proxy and base_meta and base_meta.swapped:
            raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))

        if getattr(new_clast, '_default_manager', None):
            if not is_proxy:
                # Multi-table inheritance doesn't inherit default manager from
                # parents.
                new_clast._default_manager = None
                new_clast._base_manager = None
            else:
                # Proxy clastes do inherit parent's default manager, if none is
                # set explicitly.
                new_clast._default_manager = new_clast._default_manager._copy_to_model(new_clast)
                new_clast._base_manager = new_clast._base_manager._copy_to_model(new_clast)

        # Bail out early if we have already created this clast.
        m = get_model(new_clast._meta.app_label, name,
                      seed_cache=False, only_installed=False)
        if m is not None:
            return m

        # Add all attributes to the clast.
        for obj_name, obj in attrs.items():
            new_clast.add_to_clast(obj_name, obj)

        # All the fields of any type declared on this model
        new_fields = new_clast._meta.local_fields + \
                     new_clast._meta.local_many_to_many + \
                     new_clast._meta.virtual_fields
        field_names = set([f.name for f in new_fields])

        # Basic setup for proxy models.
        if is_proxy:
            base = None
            for parent in [cls for cls in parents if hasattr(cls, '_meta')]:
                if parent._meta.abstract:
                    if parent._meta.fields:
                        raise TypeError("Abstract base clast containing model fields not permitted for proxy model '%s'." % name)
                    else:
                        continue
                if base is not None:
                    raise TypeError("Proxy model '%s' has more than one non-abstract model base clast." % name)
                else:
                    base = parent
            if base is None:
                    raise TypeError("Proxy model '%s' has no non-abstract model base clast." % name)
            if (new_clast._meta.local_fields or
                    new_clast._meta.local_many_to_many):
                raise FieldError("Proxy model '%s' contains model fields." % name)
            new_clast._meta.setup_proxy(base)
            new_clast._meta.concrete_model = base._meta.concrete_model
        else:
            new_clast._meta.concrete_model = new_clast

        # Do the appropriate setup for any model parents.
        o2o_map = dict([(f.rel.to, f) for f in new_clast._meta.local_fields
                if isinstance(f, OneToOneField)])

        for base in parents:
            original_base = base
            if not hasattr(base, '_meta'):
                # Things without _meta aren't functional models, so they're
                # uninteresting parents.
                continue

            parent_fields = base._meta.local_fields + base._meta.local_many_to_many
            # Check for clashes between locally declared fields and those
            # on the base clastes (we cannot handle shadowed fields at the
            # moment).
            for field in parent_fields:
                if field.name in field_names:
                    raise FieldError('Local field %r in clast %r clashes '
                                     'with field of similar name from '
                                     'base clast %r' %
                                        (field.name, name, base.__name__))
            if not base._meta.abstract:
                # Concrete clastes...
                base = base._meta.concrete_model
                if base in o2o_map:
                    field = o2o_map[base]
                elif not is_proxy:
                    attr_name = '%s_ptr' % base._meta.module_name
                    field = OneToOneField(base, name=attr_name,
                            auto_created=True, parent_link=True)
                    new_clast.add_to_clast(attr_name, field)
                else:
                    field = None
                new_clast._meta.parents[base] = field
            else:
                # .. and abstract ones.
                for field in parent_fields:
                    new_clast.add_to_clast(field.name, copy.deepcopy(field))

                # Past any non-abstract parent clastes onto child.
                new_clast._meta.parents.update(base._meta.parents)

            # Inherit managers from the abstract base clastes.
            new_clast.copy_managers(base._meta.abstract_managers)

            # Proxy models inherit the non-abstract managers from their base,
            # unless they have redefined any of them.
            if is_proxy:
                new_clast.copy_managers(original_base._meta.concrete_managers)

            # Inherit virtual fields (like GenericForeignKey) from the parent
            # clast
            for field in base._meta.virtual_fields:
                if base._meta.abstract and field.name in field_names:
                    raise FieldError('Local field %r in clast %r clashes '\
                                     'with field of similar name from '\
                                     'abstract base clast %r' % \
                                        (field.name, name, base.__name__))
                new_clast.add_to_clast(field.name, copy.deepcopy(field))

        if abstract:
            # Abstract base models can't be instantiated and don't appear in
            # the list of models for an app. We do the final setup for them a
            # little differently from normal models.
            attr_meta.abstract = False
            new_clast.Meta = attr_meta
            return new_clast

        new_clast._prepare()
        register_models(new_clast._meta.app_label, new_clast)

        # Because of the way imports happen (recursively), we may or may not be
        # the first time this model tries to register with the framework. There
        # should only be one clast for each model, so we always return the
        # registered version.
        return get_model(new_clast._meta.app_label, name,
                         seed_cache=False, only_installed=False)

0 View Complete Implementation : compiler.py
Copyright GNU General Public License v2.0
Author : blackye
    def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
            already_seen=None):
        """
        Returns the table alias (the name might be ambiguous, the alias will
        not be) and column name for ordering by the given 'name' parameter.
        The 'name' is of the form 'field1__field2__...__fieldN'.
        """
        name, order = get_order_dir(name, default_order)
        pieces = name.split(LOOKUP_SEP)
        field, col, alias, joins, opts = self._setup_joins(pieces, opts, alias)

        # If we get to this point and the field is a relation to another model,
        # append the default ordering for that model.
        if field.rel and len(joins) > 1 and opts.ordering:
            # Firstly, avoid infinite loops.
            if not already_seen:
                already_seen = set()
            join_tuple = tuple([self.query.alias_map[j].table_name for j in joins])
            if join_tuple in already_seen:
                raise FieldError('Infinite loop caused by ordering.')
            already_seen.add(join_tuple)

            results = []
            for item in opts.ordering:
                results.extend(self.find_ordering_name(item, opts, alias,
                        order, already_seen))
            return results
        col, alias = self._final_join_removal(col, alias)
        return [(alias, col, order)]

0 View Complete Implementation : expressions.py
Copyright GNU General Public License v2.0
Author : blackye
    def prepare_leaf(self, node, query, allow_joins):
        if not allow_joins and LOOKUP_SEP in node.name:
            raise FieldError("Joined field references are not permitted in this query")

        field_list = node.name.split(LOOKUP_SEP)
        if (len(field_list) == 1 and
            node.name in query.aggregate_select.keys()):
            self.contains_aggregate = True
            self.cols.append((node, query.aggregate_select[node.name]))
        else:
            try:
                dupe_multis = False if self.reuse is None else True
                field, source, opts, join_list, last, _ = query.setup_joins(
                    field_list, query.get_meta(), query.get_initial_alias(),
                    dupe_multis, can_reuse=self.reuse)
                col, _, join_list = query.trim_joins(source, join_list, last, False)
                if self.reuse is not None:
                    self.reuse.update(join_list)
                self.cols.append((node, (join_list[-1], col)))
            except FieldDoesNotExist:
                raise FieldError("Cannot resolve keyword %r into field. "
                                 "Choices are: %s" % (self.name,
                                                      [f.name for f in self.opts.fields]))

0 View Complete Implementation : models.py
Copyright GNU General Public License v2.0
Author : blackye
    def __new__(cls, name, bases, attrs):
        formfield_callback = attrs.pop('formfield_callback', None)
        try:
            parents = [b for b in bases if issubclast(b, ModelForm)]
        except NameError:
            # We are defining ModelForm itself.
            parents = None
        declared_fields = get_declared_fields(bases, attrs, False)
        new_clast = super(ModelFormMetaclast, cls).__new__(cls, name, bases,
                attrs)
        if not parents:
            return new_clast

        if 'media' not in attrs:
            new_clast.media = media_property(new_clast)
        opts = new_clast._meta = ModelFormOptions(getattr(new_clast, 'Meta', None))
        if opts.model:
            # If a model is defined, extract form fields from it.
            fields = fields_for_model(opts.model, opts.fields,
                                      opts.exclude, opts.widgets, formfield_callback)
            # make sure opts.fields doesn't specify an invalid field
            none_model_fields = [k for k, v in six.iteritems(fields) if not v]
            missing_fields = set(none_model_fields) - \
                             set(declared_fields.keys())
            if missing_fields:
                message = 'Unknown field(s) (%s) specified for %s'
                message = message % (', '.join(missing_fields),
                                     opts.model.__name__)
                raise FieldError(message)
            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields
        new_clast.declared_fields = declared_fields
        new_clast.base_fields = fields
        return new_clast

0 View Complete Implementation : expressions.py
Copyright MIT License
Author : bpgc-cte
    def _resolve_output_field(self):
        """
        Attempts to infer the output type of the expression. If the output
        fields of all source fields match then we can simply infer the same
        type here. This isn't always correct, but it makes sense most of the
        time.

        Consider the difference between `2 + 2` and `2 / 3`. Inferring
        the type here is a convenience for the common case. The user should
        supply their own output_field with more complex computations.

        If a source does not have an `_output_field` then we exclude it from
        this check. If all sources are `None`, then an error will be thrown
        higher up the stack in the `output_field` property.
        """
        if self._output_field is None:
            sources = self.get_source_fields()
            num_sources = len(sources)
            if num_sources == 0:
                self._output_field = None
            else:
                for source in sources:
                    if self._output_field is None:
                        self._output_field = source
                    if source is not None and not isinstance(self._output_field, source.__clast__):
                        raise FieldError(
                            "Expression contains mixed types. You must set output_field")

0 View Complete Implementation : subqueries.py
Copyright MIT License
Author : bpgc-cte
    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field = self.get_meta().get_field(name)
            direct = not (field.auto_created and not field.concrete) or not field.concrete
            model = field.model._meta.concrete_model
            if not direct or (field.is_relation and field.many_to_many):
                raise FieldError(
                    'Cannot update model field %r (only non-relations and '
                    'foreign keys permitted).' % field
                )
            if model is not self.get_meta().model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)

0 View Complete Implementation : importer.py
Copyright MIT License
Author : datosgobar
    def _run_import(self, import_all=False):
        import_config_model = ImportConfig.get_solo()
        if (not import_config_model.endpoint or
                not import_config_model.token or
                not import_config_model.kong_api_id):
            raise FieldError("Configuración de importación de yyyytics no inicializada")

        cursor = import_config_model.last_cursor or None
        if import_all:
            cursor = None

        response = self.exec_request(cursor=cursor,
                                     kong_api_id=import_config_model.kong_api_id)
        self._load_queries(response)
        next_results = response['next']
        while next_results:
            # Actualizo el cursor en cada iteración en caso de error
            import_config_model.last_cursor = parse.parse_qs(parse.urlsplit(next_results).query)['cursor'][0]
            import_config_model.save()
            response = self.exec_request(url=next_results)
            self._load_queries(response)
            next_results = response['next']

0 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def __new__(cls, name, bases, attrs):
        super_new = super(ModelBase, cls).__new__

        # six.with_metaclast() inserts an extra clast called 'NewBase' in the
        # inheritance tree: Model -> NewBase -> object. But the initialization
        # should be executed only once for a given model clast.

        # attrs will never be empty for clastes declared in the standard way
        # (ie. with the `clast` keyword). This is quite robust.
        if name == 'NewBase' and attrs == {}:
            return super_new(cls, name, bases, attrs)

        # Also ensure initialization is only performed for subclastes of Model
        # (excluding Model clast itself).
        parents = [b for b in bases if isinstance(b, ModelBase) and
                not (b.__name__ == 'NewBase' and b.__mro__ == (b, object))]
        if not parents:
            return super_new(cls, name, bases, attrs)

        # Create the clast.
        module = attrs.pop('__module__')
        new_clast = super_new(cls, name, bases, {'__module__': module})
        attr_meta = attrs.pop('Meta', None)
        abstract = getattr(attr_meta, 'abstract', False)
        if not attr_meta:
            meta = getattr(new_clast, 'Meta', None)
        else:
            meta = attr_meta
        base_meta = getattr(new_clast, '_meta', None)

        if getattr(meta, 'app_label', None) is None:
            # Figure out the app_label by looking one level up.
            # For 'django.contrib.sites.models', this would be 'sites'.
            model_module = sys.modules[new_clast.__module__]
            kwargs = {"app_label": model_module.__name__.split('.')[-2]}
        else:
            kwargs = {}

        new_clast.add_to_clast('_meta', Options(meta, **kwargs))
        if not abstract:
            new_clast.add_to_clast('DoesNotExist', subclast_exception(str('DoesNotExist'),
                    tuple(x.DoesNotExist
                          for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
                    or (ObjectDoesNotExist,),
                    module, attached_to=new_clast))
            new_clast.add_to_clast('MultipleObjectsReturned', subclast_exception(str('MultipleObjectsReturned'),
                    tuple(x.MultipleObjectsReturned
                          for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
                    or (MultipleObjectsReturned,),
                    module, attached_to=new_clast))
            if base_meta and not base_meta.abstract:
                # Non-abstract child clastes inherit some attributes from their
                # non-abstract parent (unless an ABC comes before it in the
                # method resolution order).
                if not hasattr(meta, 'ordering'):
                    new_clast._meta.ordering = base_meta.ordering
                if not hasattr(meta, 'get_latest_by'):
                    new_clast._meta.get_latest_by = base_meta.get_latest_by

        is_proxy = new_clast._meta.proxy

        # If the model is a proxy, ensure that the base clast
        # hasn't been swapped out.
        if is_proxy and base_meta and base_meta.swapped:
            raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))

        if getattr(new_clast, '_default_manager', None):
            if not is_proxy:
                # Multi-table inheritance doesn't inherit default manager from
                # parents.
                new_clast._default_manager = None
                new_clast._base_manager = None
            else:
                # Proxy clastes do inherit parent's default manager, if none is
                # set explicitly.
                new_clast._default_manager = new_clast._default_manager._copy_to_model(new_clast)
                new_clast._base_manager = new_clast._base_manager._copy_to_model(new_clast)

        # Bail out early if we have already created this clast.
        m = get_model(new_clast._meta.app_label, name,
                      seed_cache=False, only_installed=False)
        if m is not None:
            return m

        # Add all attributes to the clast.
        for obj_name, obj in attrs.items():
            new_clast.add_to_clast(obj_name, obj)

        # All the fields of any type declared on this model
        new_fields = new_clast._meta.local_fields + \
                     new_clast._meta.local_many_to_many + \
                     new_clast._meta.virtual_fields
        field_names = set([f.name for f in new_fields])

        # Basic setup for proxy models.
        if is_proxy:
            base = None
            for parent in [cls for cls in parents if hasattr(cls, '_meta')]:
                if parent._meta.abstract:
                    if parent._meta.fields:
                        raise TypeError("Abstract base clast containing model fields not permitted for proxy model '%s'." % name)
                    else:
                        continue
                if base is not None:
                    raise TypeError("Proxy model '%s' has more than one non-abstract model base clast." % name)
                else:
                    base = parent
            if base is None:
                raise TypeError("Proxy model '%s' has no non-abstract model base clast." % name)
            if (new_clast._meta.local_fields or
                    new_clast._meta.local_many_to_many):
                raise FieldError("Proxy model '%s' contains model fields." % name)
            new_clast._meta.setup_proxy(base)
            new_clast._meta.concrete_model = base._meta.concrete_model
        else:
            new_clast._meta.concrete_model = new_clast

        # Do the appropriate setup for any model parents.
        o2o_map = dict([(f.rel.to, f) for f in new_clast._meta.local_fields
                if isinstance(f, OneToOneField)])

        for base in parents:
            original_base = base
            if not hasattr(base, '_meta'):
                # Things without _meta aren't functional models, so they're
                # uninteresting parents.
                continue

            parent_fields = base._meta.local_fields + base._meta.local_many_to_many
            # Check for clashes between locally declared fields and those
            # on the base clastes (we cannot handle shadowed fields at the
            # moment).
            for field in parent_fields:
                if field.name in field_names:
                    raise FieldError('Local field %r in clast %r clashes '
                                     'with field of similar name from '
                                     'base clast %r' %
                                        (field.name, name, base.__name__))
            if not base._meta.abstract:
                # Concrete clastes...
                base = base._meta.concrete_model
                if base in o2o_map:
                    field = o2o_map[base]
                elif not is_proxy:
                    attr_name = '%s_ptr' % base._meta.model_name
                    field = OneToOneField(base, name=attr_name,
                            auto_created=True, parent_link=True)
                    new_clast.add_to_clast(attr_name, field)
                else:
                    field = None
                new_clast._meta.parents[base] = field
            else:
                # .. and abstract ones.
                for field in parent_fields:
                    new_clast.add_to_clast(field.name, copy.deepcopy(field))

                # Past any non-abstract parent clastes onto child.
                new_clast._meta.parents.update(base._meta.parents)

            # Inherit managers from the abstract base clastes.
            new_clast.copy_managers(base._meta.abstract_managers)

            # Proxy models inherit the non-abstract managers from their base,
            # unless they have redefined any of them.
            if is_proxy:
                new_clast.copy_managers(original_base._meta.concrete_managers)

            # Inherit virtual fields (like GenericForeignKey) from the parent
            # clast
            for field in base._meta.virtual_fields:
                if base._meta.abstract and field.name in field_names:
                    raise FieldError('Local field %r in clast %r clashes '\
                                     'with field of similar name from '\
                                     'abstract base clast %r' % \
                                        (field.name, name, base.__name__))
                new_clast.add_to_clast(field.name, copy.deepcopy(field))

        if abstract:
            # Abstract base models can't be instantiated and don't appear in
            # the list of models for an app. We do the final setup for them a
            # little differently from normal models.
            attr_meta.abstract = False
            new_clast.Meta = attr_meta
            return new_clast

        new_clast._prepare()
        register_models(new_clast._meta.app_label, new_clast)

        # Because of the way imports happen (recursively), we may or may not be
        # the first time this model tries to register with the framework. There
        # should only be one clast for each model, so we always return the
        # registered version.
        return get_model(new_clast._meta.app_label, name,
                         seed_cache=False, only_installed=False)

0 View Complete Implementation : expressions.py
Copyright Apache License 2.0
Author : edisonlz
    def prepare_leaf(self, node, query, allow_joins):
        if not allow_joins and LOOKUP_SEP in node.name:
            raise FieldError("Joined field references are not permitted in this query")

        field_list = node.name.split(LOOKUP_SEP)
        if node.name in query.aggregates:
            self.cols.append((node, query.aggregate_select[node.name]))
        else:
            try:
                field, sources, opts, join_list, path = query.setup_joins(
                    field_list, query.get_meta(),
                    query.get_initial_alias(), self.reuse)
                targets, _, join_list = query.trim_joins(sources, join_list, path)
                if self.reuse is not None:
                    self.reuse.update(join_list)
                for t in targets:
                    self.cols.append((node, (join_list[-1], t.column)))
            except FieldDoesNotExist:
                raise FieldError("Cannot resolve keyword %r into field. "
                                 "Choices are: %s" % (self.name,
                                                      [f.name for f in self.opts.fields]))

0 View Complete Implementation : test_encrypted.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
    def test_unsupported(self):
        with self.astertRaises(exceptions.FieldError):
            EncryptedNullableIntegerModel.objects.filter(field__exact=2)

0 View Complete Implementation : test_pickle.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
    def test_unsupported(self):
        with self.astertRaises(exceptions.FieldError):
            NullablePickledModel.objects.filter(field__contains=[2])

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : inueni
    def get_form(self, request, obj=None, **kwargs):
        if MODELADMIN_GET_EXCLUDE_SUPPORT:
            return super(SubAdminMixin, self).get_form(request, obj, **kwargs)

        if 'fields' in kwargs:
            fields = kwargs.pop('fields')
        else:
            fields = flatten_fieldsets(self.get_fieldsets(request, obj))
        excluded = self.get_exclude(request, obj)
        exclude = [] if excluded is None else list(excluded)
        readonly_fields = self.get_readonly_fields(request, obj)
        exclude.extend(readonly_fields)

        if excluded is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
            exclude.extend(self.form._meta.exclude)

        exclude = exclude or None

        new_attrs = OrderedDict(
            (f, None) for f in readonly_fields
            if f in self.form.declared_fields
        )
        
        form = type(self.form.__name__, (self.form,), new_attrs)

        defaults = {
            "form": form,
            "fields": fields,
            "exclude": exclude,
            "formfield_callback": partial(self.formfield_for_dbfield, request=request),
        }
        defaults.update(kwargs)

        if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
            defaults['fields'] = ALL_FIELDS

        try:
            return modelform_factory(self.model, **defaults)
        except FieldError as e:
            raise FieldError('%s. Check fields/fieldsets/exclude attributes of clast %s.' % (e, self.__clast__.__name__))

0 View Complete Implementation : detail.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jlmadurga
    def get_context(self, bot, update, **kwargs):
        queryset = self.get_queryset()
        if not self.slug_field: 
            raise AttributeError("Generic detail view %s must be called with "
                                 "a slug."
                                 % self.__clast__.__name__)
        slug_field = self.get_slug_field(**kwargs)
        slug = self.get_slug(**kwargs)
        if slug:
            try:
                object = queryset.get(**{slug_field: slug})
            except FieldError:
                raise FieldError("Field %s not in valid. Review slug_field" % slug_field)
            except ObjectDoesNotExist:
                object = None
        else: 
            object = None
        context = {'context_object_name': object}
        if self.context_object_name:
            context[self.context_object_name] = object
        return context

0 View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
        prefix=None,
        prefix_verbose=None,
        add_related_name=False,
        limit_content_type_choices_to={},
        limit_object_choices_to={},
        is_required=False,
    ):
    """
    returns a mixin clast for generic foreign keys using
    "Content type - object Id" with dynamic field names.
    This function is just a clast generator

    Parameters:
    prefix : a prefix, which is added in front of the fields
    prefix_verbose :    a verbose name of the prefix, used to
                        generate a satle for the field column
                        of the content object in the Admin.
    add_related_name :  a boolean value indicating, that a
                        related name for the generated content
                        type foreign key should be added. This
                        value should be true, if you use more
                        than one ObjectRelationMixin in your model.

    The model fields are created like this:

    <<prefix>>_content_type :   Field name for the "content type"
    <<prefix>>_object_id :      Field name for the "object Id"
    <<prefix>>_content_object : Field name for the "content object"

    """
    p = ""
    if prefix:
        p = "%s_" % prefix

    content_type_field = "%scontent_type" % p
    object_id_field = "%sobject_id" % p
    content_object_field = "%scontent_object" % p

    clast TheClast(models.Model):
        clast Meta:
            abstract = True

    if add_related_name:
        if not prefix:
            raise FieldError("if add_related_name is set to True, a prefix must be given")
        related_name = prefix
    else:
        related_name = None

    optional = not is_required

    ct_verbose_name = (
        _("%s's type (model)") % prefix_verbose
        if prefix_verbose
        else _("Related object's type (model)")
    )

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=ct_verbose_name,
        related_name=related_name,
        blank=optional,
        null=optional,
        help_text=_("Please select the type (model) for the relation, you want to build."),
        limit_choices_to=limit_content_type_choices_to,
    )

    fk_verbose_name = (prefix_verbose or _("Related object"))

    object_id = models.CharField(
        fk_verbose_name,
        blank=optional,
        null=False,
        help_text=_("Please enter the ID of the related object."),
        max_length=255,
        default="",  # for south migrations
    )
    object_id.limit_choices_to = limit_object_choices_to
    # can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
    content_object = GenericForeignKey(
        ct_field=content_type_field,
        fk_field=object_id_field,
    )

    TheClast.add_to_clast(content_type_field, content_type)
    TheClast.add_to_clast(object_id_field, object_id)
    TheClast.add_to_clast(content_object_field, content_object)

    return TheClast

0 View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
        prefix=None,
        prefix_verbose=None,
        add_related_name=False,
        limit_content_type_choices_to={},
        limit_object_choices_to={},
        is_required=False,
    ):
    """
    returns a mixin clast for generic foreign keys using
    "Content type - object Id" with dynamic field names.
    This function is just a clast generator

    Parameters:
    prefix : a prefix, which is added in front of the fields
    prefix_verbose :    a verbose name of the prefix, used to
                        generate a satle for the field column
                        of the content object in the Admin.
    add_related_name :  a boolean value indicating, that a
                        related name for the generated content
                        type foreign key should be added. This
                        value should be true, if you use more
                        than one ObjectRelationMixin in your model.

    The model fields are created like this:

    <<prefix>>_content_type :   Field name for the "content type"
    <<prefix>>_object_id :      Field name for the "object Id"
    <<prefix>>_content_object : Field name for the "content object"

    """
    if prefix:
        p = "%s_" % prefix
    else:
        p = ""

    content_type_field = "%scontent_type" % p
    object_id_field = "%sobject_id" % p
    content_object_field = "%scontent_object" % p

    clast TheClast(models.Model):
        clast Meta:
            abstract = True

    if add_related_name:
        if not prefix:
            raise FieldError("if add_related_name is set to True, a prefix must be given")
        related_name = prefix
    else:
        related_name = None

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=(_("%s's type (model)") % prefix_verbose
            if prefix_verbose
            else _("Related object's type (model)")
        ),
        related_name=related_name,
        blank=not is_required,
        null=not is_required,
        help_text=_("Please select the type (model) for the relation, you want to build."),
        limit_choices_to=limit_content_type_choices_to,
    )

    object_id = models.CharField(
        (prefix_verbose or _("Related object")),
        blank=not is_required,
        null=False,
        help_text=_("Please enter the ID of the related object."),
        max_length=255,
        default="",  # for south migrations
    )
    object_id.limit_choices_to = limit_object_choices_to
    # can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
    content_object = GenericForeignKey(
        ct_field=content_type_field,
        fk_field=object_id_field,
    )

    TheClast.add_to_clast(content_type_field, content_type)
    TheClast.add_to_clast(object_id_field, object_id)
    TheClast.add_to_clast(content_object_field, content_object)

    return TheClast

0 View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
        prefix=None,
        prefix_verbose=None,
        add_related_name=False,
        limit_content_type_choices_to={},
        limit_object_choices_to={},
        is_required=False,
    ):
    """
    returns a mixin clast for generic foreign keys using
    "Content type - object Id" with dynamic field names.
    This function is just a clast generator

    Parameters:
    prefix : a prefix, which is added in front of the fields
    prefix_verbose :    a verbose name of the prefix, used to
                        generate a satle for the field column
                        of the content object in the Admin.
    add_related_name :  a boolean value indicating, that a
                        related name for the generated content
                        type foreign key should be added. This
                        value should be true, if you use more
                        than one ObjectRelationMixin in your model.

    The model fields are created like this:

    <<prefix>>_content_type :   Field name for the "content type"
    <<prefix>>_object_id :      Field name for the "object Id"
    <<prefix>>_content_object : Field name for the "content object"

    """
    if prefix:
        p = "%s_" % prefix
    else:
        p = ""

    content_type_field = "%scontent_type" % p
    object_id_field = "%sobject_id" % p
    content_object_field = "%scontent_object" % p

    clast TheClast(models.Model):
        clast Meta:
            abstract = True

    if add_related_name:
        if not prefix:
            raise FieldError("if add_related_name is set to True, a prefix must be given")
        related_name = prefix
    else:
        related_name = None

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=(prefix_verbose and _("%s's type (model)") % prefix_verbose or _("Related object's type (model)")),
        related_name=related_name,
        blank=not is_required,
        null=not is_required,
        help_text=_("Please select the type (model) for the relation, you want to build."),
        limit_choices_to=limit_content_type_choices_to,
    )

    object_id = models.CharField(
        (prefix_verbose or _("Related object")),
        blank=not is_required,
        null=False,
        help_text=_("Please enter the ID of the related object."),
        max_length=255,
        default="",  # for south migrations
    )
    object_id.limit_choices_to = limit_object_choices_to
    # can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
    content_object = GenericForeignKey(
        ct_field=content_type_field,
        fk_field=object_id_field,
    )

    TheClast.add_to_clast(content_type_field, content_type)
    TheClast.add_to_clast(object_id_field, object_id)
    TheClast.add_to_clast(content_object_field, content_object)

    return TheClast

0 View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
        prefix=None,
        prefix_verbose=None,
        add_related_name=False,
        limit_content_type_choices_to={},
        limit_object_choices_to={},
        is_required=False,
    ):
    """
    returns a mixin clast for generic foreign keys using
    "Content type - object Id" with dynamic field names.
    This function is just a clast generator

    Parameters:
    prefix : a prefix, which is added in front of the fields
    prefix_verbose :    a verbose name of the prefix, used to
                        generate a satle for the field column
                        of the content object in the Admin.
    add_related_name :  a boolean value indicating, that a
                        related name for the generated content
                        type foreign key should be added. This
                        value should be true, if you use more
                        than one ObjectRelationMixin in your model.

    The model fields are created like this:

    <<prefix>>_content_type :   Field name for the "content type"
    <<prefix>>_object_id :      Field name for the "object Id"
    <<prefix>>_content_object : Field name for the "content object"

    """
    if prefix:
        p = "%s_" % prefix
    else:
        p = ""

    content_type_field = "%scontent_type" % p
    object_id_field = "%sobject_id" % p
    content_object_field = "%scontent_object" % p

    clast TheClast(models.Model):
        clast Meta:
            abstract = True

    if add_related_name:
        if not prefix:
            raise FieldError('if add_related_name is set to True, a prefix must be given')
        related_name = prefix
    else:
        related_name = None

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=(prefix_verbose and _("%s's type (model)") % prefix_verbose or _("Related object's type (model)")),
        related_name=related_name,
        blank=not is_required,
        null=not is_required,
        help_text=_("Please select the type (model) for the relation, you want to build."),
        limit_choices_to=limit_content_type_choices_to,
    )

    object_id = models.CharField(
        (prefix_verbose or _("Related object")),
        blank=not is_required,
        null=False,
        help_text=_("Please enter the ID of the related object."),
        max_length=255,
        default="",  # for south migrations
    )
    object_id.limit_choices_to = limit_object_choices_to
    # can be retrieved by MyModel._meta.get_field("object_id").limit_choices_to
    content_object = GenericForeignKey(
        ct_field=content_type_field,
        fk_field=object_id_field,
    )

    TheClast.add_to_clast(content_type_field, content_type)
    TheClast.add_to_clast(object_id_field, object_id)
    TheClast.add_to_clast(content_object_field, content_object)

    return TheClast

0 View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
def object_relation_mixin_factory(
        prefix=None,
        prefix_verbose=None,
        add_related_name=False,
        limit_content_type_choices_to=None,
        limit_object_choices_to=None,
        is_required=False):
    """
    Returns a mixin clast for generic foreign keys using
    "Content type - object ID" with dynamic field names.
    This function is just a clast generator.

    Parameters:
    prefix:           a prefix, which is added in front of
                      the fields
    prefix_verbose:   a verbose name of the prefix, used to
                      generate a satle for the field column
                      of the content object in the Admin
    add_related_name: a boolean value indicating, that a
                      related name for the generated content
                      type foreign key should be added. This
                      value should be true, if you use more
                      than one ObjectRelationMixin in your
                      model.

    The model fields are created using this naming scheme:
        <<prefix>>_content_type
        <<prefix>>_object_id
        <<prefix>>_content_object
    """
    p = ""
    if prefix:
        p = f"{prefix}_"

    prefix_verbose = prefix_verbose or _("Related object")
    limit_content_type_choices_to = limit_content_type_choices_to or {}
    limit_object_choices_to = limit_object_choices_to or {}

    content_type_field = f"{p}content_type"
    object_id_field = f"{p}object_id"
    content_object_field = f"{p}content_object"

    clast TheClast(models.Model):
        clast Meta:
            abstract = True

    if add_related_name:
        if not prefix:
            raise FieldError("if add_related_name is set to "
                             "True, a prefix must be given")
        related_name = prefix
    else:
        related_name = None

    optional = not is_required

    ct_verbose_name = _(f"{prefix_verbose}'s type (model)")

    content_type = models.ForeignKey(
        ContentType,
        verbose_name=ct_verbose_name,
        related_name=related_name,
        blank=optional,
        null=optional,
        help_text=_("Please select the type (model) "
                    "for the relation, you want to build."),
        limit_choices_to=limit_content_type_choices_to,
        on_delete=models.CASCADE)

    fk_verbose_name = prefix_verbose

    object_id = models.CharField(
        fk_verbose_name,
        blank=optional,
        null=False,
        help_text=_("Please enter the ID of the related object."),
        max_length=255,
        default="")  # for migrations
    object_id.limit_choices_to = limit_object_choices_to
    # can be retrieved by
    # MyModel._meta.get_field("object_id").limit_choices_to

    content_object = GenericForeignKey(
        ct_field=content_type_field,
        fk_field=object_id_field)

    TheClast.add_to_clast(content_type_field, content_type)
    TheClast.add_to_clast(object_id_field, object_id)
    TheClast.add_to_clast(content_object_field,
                          content_object)

    return TheClast

0 View Complete Implementation : __init__.py
Copyright ISC License
Author : percipient
    @clastmethod
    def _cmp(cls, value1, value2):
        """
        Comparison method that takes into account Django's special rules when
        ordering by a field that is a model:

            1. Try following the default ordering on the related model.
            2. Order by the model's primary key, if there is no Meta.ordering.

        """
        if isinstance(value1, Model) and isinstance(value2, Model):
            field_names = value1._meta.ordering

            # astert that the ordering is the same between different models.
            if field_names != value2._meta.ordering:
                valid_field_names = (set(cls._get_field_names(value1)) &
                                     set(cls._get_field_names(value2)))
                raise FieldError(
                    "Ordering differs between models. Choices are: %s" %
                    ', '.join(valid_field_names))

            # By default, order by the pk.
            if not field_names:
                field_names = ['pk']

            # TODO Figure out if we don't need to generate this comparator every
            # time.
            return cls._generate_comparator(field_names)(value1, value2)

        return cmp(value1, value2)

0 View Complete Implementation : subqueries.py
Copyright MIT License
Author : rizwansoaib
    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in values.items():
            field = self.get_meta().get_field(name)
            direct = not (field.auto_created and not field.concrete) or not field.concrete
            model = field.model._meta.concrete_model
            if not direct or (field.is_relation and field.many_to_many):
                raise FieldError(
                    'Cannot update model field %r (only non-relations and '
                    'foreign keys permitted).' % field
                )
            if model is not self.get_meta().concrete_model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)