Python django.core.exceptions.FieldError() Examples

The following are 30 code examples of django.core.exceptions.FieldError(). 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.core.exceptions , or try the search function .
Example #1
Source File: subqueries.py    From Hands-On-Application-Development-with-PyCharm with 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 #2
Source File: admin.py    From djangoql with 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 #3
Source File: fields.py    From django-multiupload with 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 #4
Source File: operations.py    From python with 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 #5
Source File: query.py    From GTDWeb with 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 #6
Source File: subqueries.py    From bioforum with 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 #7
Source File: query.py    From GTDWeb with 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 #8
Source File: query.py    From GTDWeb with 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 #9
Source File: subqueries.py    From GTDWeb with 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 #10
Source File: subqueries.py    From python with 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 #11
Source File: compiler.py    From python with 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 #12
Source File: query.py    From python with 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 #13
Source File: query.py    From python with 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 #14
Source File: expressions.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _output_field_or_none(self):
        """
        Return the output field of this expression, or None if
        _resolve_output_field() didn't return an output type.
        """
        try:
            return self.output_field
        except FieldError:
            if not self._output_field_resolved_to_none:
                raise 
Example #15
Source File: layer_selection.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def selected_features(self):
        """
            Returns all Feature instances in self.features
        :return:
        """

        try:
            return self.features.all()
        except FieldError:
            # Fix a terrible Django manyToMany cache initialization bug by clearing the model caches
            clear_many_cache_on_instance_field(self.features)
            return self.features.all() 
Example #16
Source File: expressions.py    From python with Apache License 2.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 #17
Source File: expressions.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 
Example #18
Source File: expressions.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def as_sqlite(self, compiler, connection, **extra_context):
        sql, params = self.as_sql(compiler, connection, **extra_context)
        try:
            if self.output_field.get_internal_type() == 'DecimalField':
                sql = 'CAST(%s AS NUMERIC)' % sql
        except FieldError:
            pass
        return sql, params 
Example #19
Source File: aggregates.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 
Example #20
Source File: expressions.py    From python with Apache License 2.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 #21
Source File: expressions.py    From python with Apache License 2.0 5 votes vote down vote up
def as_sqlite(self, compiler, connection, **extra_context):
        sql, params = self.as_sql(compiler, connection, **extra_context)
        try:
            if self.output_field.get_internal_type() == 'DecimalField':
                sql = 'CAST(%s AS NUMERIC)' % sql
        except FieldError:
            pass
        return sql, params 
Example #22
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 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):
            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 #23
Source File: mixins.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def filter_queryset(self, request, queryset, *args):
        for param_name, param_value in request.GET.items():
            try:
                if param_name.endswith('_contains'):
                    param_name = param_name.replace('_contains', '__icontains')
                queryset = queryset.filter(**{param_name: param_value})
            except FieldError:
                continue
        return queryset 
Example #24
Source File: reverse_related.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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] 
Example #25
Source File: edit.py    From django_OA with GNU General Public License v3.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 #26
Source File: test_query.py    From django-mock-queries with MIT License 5 votes vote down vote up
def test_query_values_list_raises_attribute_error_when_field_is_not_in_meta_concrete_fields(self):
        qs = MockSet(MockModel(foo=1), MockModel(foo=2))
        self.assertRaises(FieldError, qs.values_list, 'bar') 
Example #27
Source File: test_query.py    From django-mock-queries with MIT License 5 votes vote down vote up
def test_query_update_does_not_allow_related_model_fields(self):
        objects = [MockModel(foo=MockModel(bar=1)), MockModel(foo=MockModel(bar=2))]
        qs = MockSet(*objects, model=create_model('foo'))

        target = dict(foo__bar=2)
        with self.assertRaises(FieldError) as cm:
            qs.update(**target)

        assert 'Cannot update model field \'{}\''.format(next(iter(target))) in str(cm.exception) 
Example #28
Source File: test_query.py    From django-mock-queries with MIT License 5 votes vote down vote up
def test_query_create_raises_value_error_when_kwarg_key_is_not_in_concrete_fields(self):
        qs = MockSet(
            model=create_model('first', 'second', 'third')
        )
        attrs = dict(first=1, second=2, third=3, fourth=4)
        with self.assertRaises(FieldError):
            qs.create(**attrs) 
Example #29
Source File: test_query.py    From django-mock-queries with MIT License 5 votes vote down vote up
def test_query_filters_model_objects_by_bad_field(self):
        item_1 = Car(speed=1)
        item_2 = Sedan(speed=2)
        item_3 = Car(speed=3)

        item_2.sedan = item_2

        self.mock_set.add(item_1, item_2, item_3)
        with self.assertRaisesRegexp(
                FieldError,
                r"Cannot resolve keyword 'bad_field' into field\. "
                r"Choices are 'id', 'make', 'make_id', 'model', 'passengers', 'sedan', 'speed', 'variations'\."):
            self.mock_set.filter(bad_field='bogus') 
Example #30
Source File: utils.py    From django-mock-queries with MIT License 5 votes vote down vote up
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)