Python django.core.exceptions.FieldError() Examples

The following are 30 code examples for showing how to use django.core.exceptions.FieldError(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.exceptions , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: subqueries.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 2
Project: GTDWeb   Author: lanbing510   File: query.py    License: GNU General Public License v2.0 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 3
Project: GTDWeb   Author: lanbing510   File: query.py    License: GNU General Public License v2.0 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 4
Project: GTDWeb   Author: lanbing510   File: query.py    License: GNU General Public License v2.0 6 votes vote down vote up
def add_ordering(self, *ordering):
        """
        Adds items from the 'ordering' sequence to the query's "order by"
        clause. These items are either field names (not column names) --
        possibly with a direction prefix ('-' or '?') -- or OrderBy
        expressions.

        If 'ordering' is empty, all ordering is cleared from the query.
        """
        errors = []
        for item in ordering:
            if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item):
                errors.append(item)
        if errors:
            raise FieldError('Invalid order_by arguments: %s' % errors)
        if ordering:
            self.order_by.extend(ordering)
        else:
            self.default_ordering = False 
Example 5
Project: django-multiupload   Author: Chive   File: fields.py    License: MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.media_type = kwargs.pop('media_type', 'image')

        if self.media_type not in MEDIA_TYPES:
            raise FieldError(
                self.error_messages['wrong_type'] % {
                    'valid_types': ', '.join(MEDIA_TYPES),
                }
            )

        kwargs.update({
            'attrs': {
                'accept': '{0}/*'.format(self.media_type),
            }
        })
        super(MultiMediaField, self).__init__(*args, **kwargs) 
Example 6
Project: bioforum   Author: reBiocoder   File: operations.py    License: MIT License 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass
                else:
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        ) 
Example 7
Project: bioforum   Author: reBiocoder   File: subqueries.py    License: MIT License 6 votes vote down vote up
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().model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq) 
Example 8
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: operations.py    License: MIT License 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass
                else:
                    if isinstance(output_field, bad_fields):
                        raise utils.NotSupportedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        ) 
Example 9
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: subqueries.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: djangoql   Author: ivelum   File: admin.py    License: MIT License 6 votes vote down vote up
def get_search_results(self, request, queryset, search_term):
        if (
            self.search_mode_toggle_enabled() and
            not self.djangoql_search_enabled(request)
        ):
            return super(DjangoQLSearchMixin, self).get_search_results(
                request=request,
                queryset=queryset,
                search_term=search_term,
            )
        use_distinct = False
        if not search_term:
            return queryset, use_distinct
        try:
            return (
                apply_search(queryset, search_term, self.djangoql_schema),
                use_distinct,
            )
        except (DjangoQLError, ValueError, FieldError, ValidationError) as e:
            msg = self.djangoql_error_message(e)
            messages.add_message(request, messages.WARNING, msg)
            return queryset.none(), use_distinct 
Example 11
Project: python   Author: Yeah-Kun   File: operations.py    License: Apache License 2.0 6 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            for expr in expression.get_source_expressions():
                try:
                    output_field = expr.output_field
                    if isinstance(output_field, bad_fields):
                        raise NotImplementedError(
                            'You cannot use Sum, Avg, StdDev, and Variance '
                            'aggregations on date/time fields in sqlite3 '
                            'since date/time is saved as text.'
                        )
                except FieldError:
                    # Not every subexpression has an output_field which is fine
                    # to ignore.
                    pass 
Example 12
Project: python   Author: Yeah-Kun   File: subqueries.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 13
Project: python   Author: Yeah-Kun   File: compiler.py    License: Apache License 2.0 6 votes vote down vote up
def prepare_value(self, field, value):
        """
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        """
        if hasattr(value, 'resolve_expression'):
            value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
            # Don't allow values containing Col expressions. They refer to
            # existing columns on a row, but in the case of insert the row
            # doesn't exist yet.
            if value.contains_column_references:
                raise ValueError(
                    'Failed to insert expression "%s" on %s. F() expressions '
                    'can only be used to update, not to insert.' % (value, field)
                )
            if value.contains_aggregate:
                raise FieldError("Aggregate functions are not allowed in this query")
        else:
            value = field.get_db_prep_save(value, connection=self.connection)
        return value 
Example 14
Project: python   Author: Yeah-Kun   File: query.py    License: Apache License 2.0 6 votes vote down vote up
def solve_lookup_type(self, lookup):
        """
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        """
        lookup_splitted = lookup.split(LOOKUP_SEP)
        if self._annotations:
            expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
            if expression:
                return expression_lookups, (), expression
        _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
        field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
        if len(lookup_parts) == 0:
            lookup_parts = ['exact']
        elif len(lookup_parts) > 1:
            if not field_parts:
                raise FieldError(
                    'Invalid lookup "%s" for model %s".' %
                    (lookup, self.get_meta().model.__name__))
        return lookup_parts, field_parts, False 
Example 15
Project: python   Author: Yeah-Kun   File: query.py    License: Apache License 2.0 6 votes vote down vote up
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
        if not allow_joins and LOOKUP_SEP in name:
            raise FieldError("Joined field references are not permitted in this query")
        if name in self.annotations:
            if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                return Ref(name, self.annotation_select[name])
            else:
                return self.annotation_select[name]
        else:
            field_list = name.split(LOOKUP_SEP)
            field, sources, opts, join_list, path = self.setup_joins(
                field_list, self.get_meta(),
                self.get_initial_alias(), reuse)
            targets, _, join_list = self.trim_joins(sources, join_list, path)
            if len(targets) > 1:
                raise FieldError("Referencing multicolumn fields with F() objects "
                                 "isn't supported")
            if reuse is not None:
                reuse.update(join_list)
            col = targets[0].get_col(join_list[-1], sources[0])
            return col 
Example 16
Project: StormOnline   Author: stormsha   File: edit.py    License: Apache License 2.0 5 votes vote down vote up
def get_model_form(self, **kwargs):
        """
        Returns a Form class 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 pass 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 class %s.'
                             % (e, self.__class__.__name__)) 
Example 17
Project: django-webpush   Author: safwanrahman   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
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') 
Example 18
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_expression_support(self, expression):
        bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField)
        bad_aggregates = (aggregates.Sum, aggregates.Avg, aggregates.Variance, aggregates.StdDev)
        if isinstance(expression, bad_aggregates):
            try:
                output_field = expression.input_field.output_field
                if isinstance(output_field, bad_fields):
                    raise NotImplementedError(
                        'You cannot use Sum, Avg, StdDev and Variance aggregations '
                        'on date/time fields in sqlite3 '
                        'since date/time is saved as text.')
            except FieldError:
                # not every sub-expression has an output_field which is fine to
                # ignore
                pass 
Example 19
Project: GTDWeb   Author: lanbing510   File: aggregates.py    License: GNU General Public License v2.0 5 votes vote down vote up
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        assert len(self.source_expressions) == 1
        # Aggregates are not allowed in UPDATE queries, so ignore for_save
        c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
        if c.source_expressions[0].contains_aggregate and not summarize:
            name = self.source_expressions[0].name
            raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (
                c.name, name, name))
        c._patch_aggregate(query)  # backward-compatibility support
        return c 
Example 20
Project: GTDWeb   Author: lanbing510   File: expressions.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 21
Project: GTDWeb   Author: lanbing510   File: expressions.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _output_field_or_none(self):
        """
        Returns the output field of this expression, or None if no output type
        can be resolved. Note that the 'output_field' property will raise
        FieldError if no type can be resolved, but this attribute allows for
        None values.
        """
        if self._output_field is None:
            self._resolve_output_field()
        return self._output_field 
Example 22
Project: GTDWeb   Author: lanbing510   File: expressions.py    License: GNU General Public License v2.0 5 votes vote down vote up
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.__class__):
                        raise FieldError(
                            "Expression contains mixed types. You must set output_field") 
Example 23
Project: GTDWeb   Author: lanbing510   File: expressions.py    License: GNU General Public License v2.0 5 votes vote down vote up
def compile(self, side, compiler, connection):
        if not isinstance(side, DurationValue):
            try:
                output = side.output_field
            except FieldError:
                pass
            else:
                if output.get_internal_type() == 'DurationField':
                    sql, params = compiler.compile(side)
                    return connection.ops.format_for_duration_arithmetic(sql), params
        return compiler.compile(side) 
Example 24
Project: GTDWeb   Author: lanbing510   File: compiler.py    License: GNU General Public License v2.0 5 votes vote down vote up
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)
        descending = True if order == 'DESC' else False
        pieces = name.split(LOOKUP_SEP)
        field, targets, alias, joins, path, 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 unless the attribute name
        # of the field is specified.
        if field.rel and path and opts.ordering and name != field.attname:
            # 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
        targets, alias, _ = self.query.trim_joins(targets, joins, path)
        return [(OrderBy(t.get_col(alias), descending=descending), False) for t in targets] 
Example 25
Project: GTDWeb   Author: lanbing510   File: query.py    License: GNU General Public License v2.0 5 votes vote down vote up
def add_fields(self, field_names, allow_m2m=True):
        """
        Adds the given (model) fields to the select set. The field names are
        added in the order specified.
        """
        alias = self.get_initial_alias()
        opts = self.get_meta()

        try:
            for name in field_names:
                # Join promotion note - we must not remove any rows here, so
                # if there is no existing joins, use outer join.
                _, targets, _, joins, path = self.setup_joins(
                    name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
                targets, final_alias, joins = self.trim_joins(targets, joins, path)
                for target in targets:
                    self.add_select(target.get_col(final_alias))
        except MultiJoin:
            raise FieldError("Invalid field name: '%s'" % name)
        except FieldError:
            if LOOKUP_SEP in name:
                # For lookups spanning over relationships, show the error
                # from the model on which the lookup failed.
                raise
            else:
                names = sorted(list(get_field_names_from_opts(opts)) + list(self.extra)
                               + list(self.annotation_select))
                raise FieldError("Cannot resolve keyword %r into field. "
                                 "Choices are: %s" % (name, ", ".join(names))) 
Example 26
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unsupported(self):
        with self.assertRaises(exceptions.FieldError):
            EncryptedNullableIntegerModel.objects.filter(field__exact=2) 
Example 27
Project: django-cryptography   Author: georgemarshall   File: test_pickle.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unsupported(self):
        with self.assertRaises(exceptions.FieldError):
            NullablePickledModel.objects.filter(field__contains=[2]) 
Example 28
Project: koku   Author: project-koku   File: view.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def check_fields(dict_, model, exception):
        """Check if GET fields are valid."""
        valid_query_params = ["limit", "offset", "source_uuid", "ordering"]
        cost_models_params = {k: dict_.get(k) for k in dict_.keys() if k not in valid_query_params}
        try:
            model.objects.filter(**cost_models_params)
        except FieldError as fe:
            raise exception(fe) 
Example 29
Project: django-test-migrations   Author: wemake-services   File: test_pytest_plugin_reverse.py    License: MIT License 5 votes vote down vote up
def test_pytest_plugin0001(migrator):
    """Ensures that the first migration works."""
    old_state = migrator.apply_initial_migration(
        ('main_app', '0002_someitem_is_clean'),
    )
    SomeItem = old_state.apps.get_model('main_app', 'SomeItem')

    assert SomeItem.objects.filter(is_clean=True).count() == 0

    new_state = migrator.apply_tested_migration(('main_app', '0001_initial'))
    SomeItem = new_state.apps.get_model('main_app', 'SomeItem')

    with pytest.raises(FieldError):
        SomeItem.objects.filter(is_clean=True) 
Example 30
Project: django-test-migrations   Author: wemake-services   File: test_pytest_plugin_direct.py    License: MIT License 5 votes vote down vote up
def test_pytest_plugin0001(migrator):
    """Ensures that the first migration works."""
    old_state = migrator.apply_initial_migration(('main_app', '0001_initial'))
    SomeItem = old_state.apps.get_model('main_app', 'SomeItem')

    with pytest.raises(FieldError):
        SomeItem.objects.filter(is_clean=True)

    new_state = migrator.apply_tested_migration(
        ('main_app', '0002_someitem_is_clean'),
    )
    SomeItem = new_state.apps.get_model('main_app', 'SomeItem')

    assert SomeItem.objects.filter(is_clean=True).count() == 0