Python django.core.exceptions.FieldDoesNotExist() Examples

The following are 30 code examples for showing how to use django.core.exceptions.FieldDoesNotExist(). 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: checks.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _check_raw_id_fields_item(self, cls, model, field_name, label):
        """ Check an item of `raw_id_fields`, i.e. check that field named
        `field_name` exists in model `model` and is a ForeignKey or a
        ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E002')
        else:
            if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
                return must_be('a ForeignKey or ManyToManyField',
                               option=label, obj=cls, id='admin.E003')
            else:
                return [] 
Example 2
Project: GTDWeb   Author: lanbing510   File: checks.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _check_radio_fields_key(self, cls, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
Example 3
Project: GTDWeb   Author: lanbing510   File: checks.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _check_readonly_fields_item(self, cls, model, field_name, label):
        if callable(field_name):
            return []
        elif hasattr(cls, field_name):
            return []
        elif hasattr(model, field_name):
            return []
        else:
            try:
                model._meta.get_field(field_name)
            except FieldDoesNotExist:
                return [
                    checks.Error(
                        "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % (
                            label, cls.__name__, model._meta.app_label, model._meta.object_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E035',
                    )
                ]
            else:
                return [] 
Example 4
Project: GTDWeb   Author: lanbing510   File: checks.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _check_date_hierarchy(self, cls, model):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if cls.date_hierarchy is None:
            return []
        else:
            try:
                field = model._meta.get_field(cls.date_hierarchy)
            except FieldDoesNotExist:
                return refer_to_missing_field(option='date_hierarchy',
                                              field=cls.date_hierarchy,
                                              model=model, obj=cls, id='admin.E127')
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy',
                                   obj=cls, id='admin.E128')
                else:
                    return [] 
Example 5
Project: GTDWeb   Author: lanbing510   File: validation.py    License: GNU General Public License v2.0 6 votes vote down vote up
def validate_readonly_fields(self, cls, model):
        " Validate that readonly_fields refers to proper attribute or field. "
        if hasattr(cls, "readonly_fields"):
            check_isseq(cls, "readonly_fields", cls.readonly_fields)
            for idx, field in enumerate(cls.readonly_fields):
                if not callable(field):
                    if not hasattr(cls, field):
                        if not hasattr(model, field):
                            try:
                                model._meta.get_field(field)
                            except FieldDoesNotExist:
                                raise ImproperlyConfigured(
                                    "%s.readonly_fields[%d], %r is not a callable or "
                                    "an attribute of %r or found in the model %r."
                                    % (cls.__name__, idx, field, cls.__name__, model._meta.object_name)
                                ) 
Example 6
Project: django-osm-field   Author: MarkusH   File: fields.py    License: MIT License 6 votes vote down vote up
def _check_latitude_field(self):
        opts = self.model._meta
        try:
            opts.get_field(self.latitude_field_name)
        except FieldDoesNotExist:
            return [
                checks.Error(
                    "The OSMField '%s' references the non-existent latitude field '%s'."
                    % (self.name, self.latitude_field_name,),
                    hint=None,
                    obj=self,
                    id="osm_field.E001",
                )
            ]
        else:
            return [] 
Example 7
Project: django-osm-field   Author: MarkusH   File: fields.py    License: MIT License 6 votes vote down vote up
def _check_longitude_field(self):
        opts = self.model._meta
        try:
            opts.get_field(self.longitude_field_name)
        except FieldDoesNotExist:
            return [
                checks.Error(
                    "The OSMField '%s' references the non-existent "
                    "longitude field '%s'." % (self.name, self.longitude_field_name,),
                    hint=None,
                    obj=self,
                    id="osm_field.E002",
                )
            ]
        else:
            return [] 
Example 8
Project: bioforum   Author: reBiocoder   File: options.py    License: MIT License 6 votes vote down vote up
def get_field(self, field_name):
        """
        Return a field instance given the name of a forward or reverse field.
        """
        try:
            # In order to avoid premature loading of the relation tree
            # (expensive) we prefer checking if the field is a forward field.
            return self._forward_fields_map[field_name]
        except KeyError:
            # If the app registry is not ready, reverse fields are
            # unavailable, therefore we throw a FieldDoesNotExist exception.
            if not self.apps.models_ready:
                raise FieldDoesNotExist(
                    "%s has no field named '%s'. The app cache isn't ready yet, "
                    "so if this is an auto-created related field, it won't "
                    "be available yet." % (self.object_name, field_name)
                )

        try:
            # Retrieve field instance by name from cached or just-computed
            # field map.
            return self.fields_map[field_name]
        except KeyError:
            raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) 
Example 9
Project: bioforum   Author: reBiocoder   File: related.py    License: MIT License 6 votes vote down vote up
def _check_to_fields_exist(self):
        # Skip nonexistent models.
        if isinstance(self.remote_field.model, str):
            return []

        errors = []
        for to_field in self.to_fields:
            if to_field:
                try:
                    self.remote_field.model._meta.get_field(to_field)
                except exceptions.FieldDoesNotExist:
                    errors.append(
                        checks.Error(
                            "The to_field '%s' doesn't exist on the related "
                            "model '%s'."
                            % (to_field, self.remote_field.model._meta.label),
                            obj=self,
                            id='fields.E312',
                        )
                    )
        return errors 
Example 10
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def lookup_field(name, obj, model_admin=None):
    opts = obj._meta
    try:
        f = _get_non_gfk_field(opts, name)
    except (FieldDoesNotExist, FieldIsAForeignKeyColumnName):
        # For non-field values, the value is either a method, property or
        # returned via a callable.
        if callable(name):
            attr = name
            value = attr(obj)
        elif model_admin is not None and hasattr(model_admin, name) and name != '__str__':
            attr = getattr(model_admin, name)
            value = attr(obj)
        else:
            attr = getattr(obj, name)
            if callable(attr):
                value = attr()
            else:
                value = attr
        f = None
    else:
        attr = None
        value = getattr(obj, name)
    return f, attr, value 
Example 11
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def _get_non_gfk_field(opts, name):
    """
    For historical reasons, the admin app relies on GenericForeignKeys as being
    "not found" by get_field(). This could likely be cleaned up.

    Reverse relations should also be excluded as these aren't attributes of the
    model (rather something like `foo_set`).
    """
    field = opts.get_field(name)
    if (field.is_relation and
            # Generic foreign keys OR reverse relations
            ((field.many_to_one and not field.related_model) or field.one_to_many)):
        raise FieldDoesNotExist()

    # Avoid coercing <FK>_id fields to FK
    if field.is_relation and not field.many_to_many and hasattr(field, 'attname') and field.attname == name:
        raise FieldIsAForeignKeyColumnName()

    return field 
Example 12
Project: bioforum   Author: reBiocoder   File: checks.py    License: MIT License 6 votes vote down vote up
def _check_raw_id_fields_item(self, obj, model, field_name, label):
        """ Check an item of `raw_id_fields`, i.e. check that field named
        `field_name` exists in model `model` and is a ForeignKey or a
        ManyToManyField. """

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

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        obj=obj.__class__,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
Example 14
Project: bioforum   Author: reBiocoder   File: checks.py    License: MIT License 6 votes vote down vote up
def _check_prepopulated_fields_key(self, obj, model, field_name, label):
        """ Check a key of `prepopulated_fields` dictionary, i.e. check that it
        is a name of existing field and the field is one of the allowed types.
        """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E027')
        else:
            if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which must not be a DateTimeField, "
                        "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name),
                        obj=obj.__class__,
                        id='admin.E028',
                    )
                ]
            else:
                return [] 
Example 15
Project: bioforum   Author: reBiocoder   File: checks.py    License: MIT License 6 votes vote down vote up
def _check_readonly_fields_item(self, obj, model, field_name, label):
        if callable(field_name):
            return []
        elif hasattr(obj, field_name):
            return []
        elif hasattr(model, field_name):
            return []
        else:
            try:
                model._meta.get_field(field_name)
            except FieldDoesNotExist:
                return [
                    checks.Error(
                        "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % (
                            label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
                        ),
                        obj=obj.__class__,
                        id='admin.E035',
                    )
                ]
            else:
                return [] 
Example 16
Project: django-composite-foreignkey   Author: onysos   File: fields.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _check_recursion_field_dependecy(self):
        res = []
        for local_field in self._raw_fields.values():
            try:
                f = self.model._meta.get_field(local_field.value)
                if isinstance(f, CompositeForeignKey):
                    res.append(
                        checks.Error(
                            "the field %s depend on the field %s which is another CompositeForeignKey" %
                            (self.name, local_field),
                            hint=None,
                            obj=self,
                            id='compositefk.E005',
                        )
                    )
            except FieldDoesNotExist:
                pass  # _check_to_fields_local_valide already raise errors for this
        return res 
Example 17
Project: django-composite-foreignkey   Author: onysos   File: fields.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _check_to_fields_local_valide(self):
        res = []
        for local_field in self._raw_fields.values():
            if isinstance(local_field, LocalFieldValue):
                try:
                    self.model._meta.get_field(local_field.value)
                except FieldDoesNotExist:
                    res.append(
                        checks.Error(
                            "the field %s does not exists on the model %s" % (local_field, self.model),
                            hint=None,
                            obj=self,
                            id='compositefk.E003',
                        )
                    )
        return res 
Example 18
Project: tom_base   Author: TOMToolkit   File: target_list_latex_processor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_latex_table_data(self, cleaned_data):
        # TODO: enable user to modify column header
        # TODO: add preview PDF
        target_list = TargetList.objects.get(pk=cleaned_data.get('model_pk'))

        table_data = {}
        for field in cleaned_data.get('field_list', []):
            for target in target_list.targets.all():
                try:
                    verbose_name = Target._meta.get_field(field).verbose_name
                    table_data.setdefault(verbose_name, []).append(getattr(target, field))
                except FieldDoesNotExist:
                    table_data.setdefault(field, []).append(TargetExtra.objects.filter(target=target,
                                                                                       key=field).first().value)

        return table_data 
Example 19
Project: django-cassandra-engine   Author: r4fek   File: tests.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_get_fields_only_searches_forward_on_apps_not_ready(self):
        opts = CassandraThing._meta
        # If apps registry is not ready, get_field() searches over only
        # forward fields.
        opts.apps.models_ready = False
        try:
            # 'data_abstract' is a forward field, and therefore will be found
            self.assertTrue(opts.get_field('data_abstract'))
            msg = (
                "CassandraThing has no field named 'relating_baseperson'. The app "
                "cache isn't ready yet, so if this is an auto-created related "
                "field, it won't be available yet."
            )
            # 'data_abstract' is a reverse field, and will raise an exception
            with self.assertRaisesMessage(FieldDoesNotExist, msg):
                opts.get_field('relating_baseperson')
        finally:
            opts.apps.models_ready = True 
Example 20
Project: opencraft   Author: open-craft   File: test_migrate_ephemeral.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_no_instances(self):
        """
        Verify that the command correctly notifies the user that there are no instances for migration.
        """
        try:
            with LogCapture() as captured_logs:
                call_command(
                    'migrate_ephemeral',
                    stdout=StringIO(),
                )
                # Verify the logs
                self.assertIn(
                    'Found "0" instances using ephemeral databases',
                    [l[2] for l in captured_logs.actual()])
        except FieldDoesNotExist:
            # Field already removed from database
            pass 
Example 21
def to_internal_value(self, data):
        if sc.has_features(data):
            for feat in data['features']:
                return self.to_internal_value(feat)
        try:
            sref = SpatialReference(data['crs']['properties']['name'])
        except KeyError:
            sref = None
        # Force evaluation of fields property.
        if not self.fields and self.Meta.geom_field is None:
            raise exceptions.FieldDoesNotExist('Geometry field not found')
        record = {self.Meta.geom_field: data.get('geometry')}
        record.update(data.get('properties', {}))
        feature = super(FeatureSerializer, self).to_internal_value(record)
        if feature and sref:
            geom = feature[self.Meta.geom_field]
            geom.srid = sref.srid
        return feature 
Example 22
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: options.py    License: MIT License 6 votes vote down vote up
def get_field(self, field_name):
        """
        Return a field instance given the name of a forward or reverse field.
        """
        try:
            # In order to avoid premature loading of the relation tree
            # (expensive) we prefer checking if the field is a forward field.
            return self._forward_fields_map[field_name]
        except KeyError:
            # If the app registry is not ready, reverse fields are
            # unavailable, therefore we throw a FieldDoesNotExist exception.
            if not self.apps.models_ready:
                raise FieldDoesNotExist(
                    "%s has no field named '%s'. The app cache isn't ready yet, "
                    "so if this is an auto-created related field, it won't "
                    "be available yet." % (self.object_name, field_name)
                )

        try:
            # Retrieve field instance by name from cached or just-computed
            # field map.
            return self.fields_map[field_name]
        except KeyError:
            raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) 
Example 23
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: related.py    License: MIT License 6 votes vote down vote up
def _check_to_fields_exist(self):
        # Skip nonexistent models.
        if isinstance(self.remote_field.model, str):
            return []

        errors = []
        for to_field in self.to_fields:
            if to_field:
                try:
                    self.remote_field.model._meta.get_field(to_field)
                except exceptions.FieldDoesNotExist:
                    errors.append(
                        checks.Error(
                            "The to_field '%s' doesn't exist on the related "
                            "model '%s'."
                            % (to_field, self.remote_field.model._meta.label),
                            obj=self,
                            id='fields.E312',
                        )
                    )
        return errors 
Example 24
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
def lookup_needs_distinct(opts, lookup_path):
    """
    Return True if 'distinct()' should be used to query the given lookup path.
    """
    lookup_fields = lookup_path.split(LOOKUP_SEP)
    # Go through the fields (following all relations) and look for an m2m.
    for field_name in lookup_fields:
        if field_name == 'pk':
            field_name = opts.pk.name
        try:
            field = opts.get_field(field_name)
        except FieldDoesNotExist:
            # Ignore query lookups.
            continue
        else:
            if hasattr(field, 'get_path_info'):
                # This field is a relation; update opts to follow the relation.
                path_info = field.get_path_info()
                opts = path_info[-1].to_opts
                if any(path.m2m for path in path_info):
                    # This field is a m2m relation so distinct must be called.
                    return True
    return False 
Example 25
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
def lookup_field(name, obj, model_admin=None):
    opts = obj._meta
    try:
        f = _get_non_gfk_field(opts, name)
    except (FieldDoesNotExist, FieldIsAForeignKeyColumnName):
        # For non-field values, the value is either a method, property or
        # returned via a callable.
        if callable(name):
            attr = name
            value = attr(obj)
        elif hasattr(model_admin, name) and name != '__str__':
            attr = getattr(model_admin, name)
            value = attr(obj)
        else:
            attr = getattr(obj, name)
            if callable(attr):
                value = attr()
            else:
                value = attr
        f = None
    else:
        attr = None
        value = getattr(obj, name)
    return f, attr, value 
Example 26
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: utils.py    License: MIT License 6 votes vote down vote up
def _get_non_gfk_field(opts, name):
    """
    For historical reasons, the admin app relies on GenericForeignKeys as being
    "not found" by get_field(). This could likely be cleaned up.

    Reverse relations should also be excluded as these aren't attributes of the
    model (rather something like `foo_set`).
    """
    field = opts.get_field(name)
    if (field.is_relation and
            # Generic foreign keys OR reverse relations
            ((field.many_to_one and not field.related_model) or field.one_to_many)):
        raise FieldDoesNotExist()

    # Avoid coercing <FK>_id fields to FK
    if field.is_relation and not field.many_to_many and hasattr(field, 'attname') and field.attname == name:
        raise FieldIsAForeignKeyColumnName()

    return field 
Example 27
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: checks.py    License: MIT License 6 votes vote down vote up
def _check_raw_id_fields_item(self, obj, model, field_name, label):
        """ Check an item of `raw_id_fields`, i.e. check that field named
        `field_name` exists in model `model` and is a ForeignKey or a
        ManyToManyField. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=obj, id='admin.E002')
        else:
            if not field.many_to_many and not isinstance(field, models.ForeignKey):
                return must_be('a foreign key or a many-to-many field',
                               option=label, obj=obj, id='admin.E003')
            else:
                return [] 
Example 28
Project: GTDWeb   Author: lanbing510   File: query_utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __get__(self, instance, owner):
        """
        Retrieves and caches the value from the datastore on the first lookup.
        Returns the cached value.
        """
        non_deferred_model = instance._meta.proxy_for_model
        opts = non_deferred_model._meta

        assert instance is not None
        data = instance.__dict__
        if data.get(self.field_name, self) is self:
            # self.field_name is the attname of the field, but only() takes the
            # actual name, so we need to translate it here.
            try:
                f = opts.get_field(self.field_name)
            except FieldDoesNotExist:
                f = [f for f in opts.fields if f.attname == self.field_name][0]
            name = f.name
            # Let's see if the field is part of the parent chain. If so we
            # might be able to reuse the already loaded value. Refs #18343.
            val = self._check_parent_chain(instance, name)
            if val is None:
                instance.refresh_from_db(fields=[self.field_name])
                val = getattr(instance, self.field_name)
            data[self.field_name] = val
        return data[self.field_name] 
Example 29
Project: GTDWeb   Author: lanbing510   File: options.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _prepare(self, model):
        if self.order_with_respect_to:
            # The app registry will not be ready at this point, so we cannot
            # use get_field().
            query = self.order_with_respect_to
            try:
                self.order_with_respect_to = next(
                    f for f in self._get_fields(reverse=False)
                    if f.name == query or f.attname == query
                )
            except StopIteration:
                raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, query))

            self.ordering = ('_order',)
            if not any(isinstance(field, OrderWrt) for field in model._meta.local_fields):
                model.add_to_class('_order', OrderWrt())
        else:
            self.order_with_respect_to = None

        if self.pk is None:
            if self.parents:
                # Promote the first parent link in lieu of adding yet another
                # field.
                field = next(six.itervalues(self.parents))
                # Look for a local field with the same name as the
                # first parent link. If a local field has already been
                # created, use it instead of promoting the parent
                already_created = [fld for fld in self.local_fields if fld.name == field.name]
                if already_created:
                    field = already_created[0]
                field.primary_key = True
                self.setup_pk(field)
            else:
                auto = AutoField(verbose_name='ID', primary_key=True,
                        auto_created=True)
                model.add_to_class('id', auto) 
Example 30
Project: GTDWeb   Author: lanbing510   File: related.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_related_field(self):
        """
        Returns the Field in the 'to' object to which this relationship is
        tied.
        """
        field = self.to._meta.get_field(self.field_name)
        if not field.concrete:
            raise FieldDoesNotExist("No related field named '%s'" %
                    self.field_name)
        return field