Python django.core.checks.Error() Examples

The following are 30 code examples of django.core.checks.Error(). 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.checks , or try the search function .
Example #1
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_on_delete(self):
        on_delete = getattr(self.rel, 'on_delete', None)
        if on_delete == SET_NULL and not self.null:
            return [
                checks.Error(
                    'Field specifies on_delete=SET_NULL, but cannot be null.',
                    hint='Set null=True argument on the field, or change the on_delete rule.',
                    obj=self,
                    id='fields.E320',
                )
            ]
        elif on_delete == SET_DEFAULT and not self.has_default():
            return [
                checks.Error(
                    'Field specifies on_delete=SET_DEFAULT, but has no default value.',
                    hint='Set a default value, or change the on_delete rule.',
                    obj=self,
                    id='fields.E321',
                )
            ]
        else:
            return [] 
Example #2
Source File: checks.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def geoip_db_is_available(app_configs, **kwargs):
    errors = []
    if geolocation.geoip_reader is None:
        # try loading it
        geolocation.load_geoip_database()
        if geolocation.geoip_reader is None:
            errors.append(Error("GeoIP DB not available", id=ERROR_GEOIP_DB_NOT_AVAILABLE))

    if not errors:
        # DB seems to be available, try and do a lookup that should resolve to
        # some country. The specific country isn't important.
        ip = "1.2.3.4"
        country = geolocation.get_country_code(ip)
        if country is None:
            errors.append(
                Error(
                    f"GeoIP DB returned no country for {ip!r}", id=ERROR_GEOIP_DB_UNEXPECTED_RESULT
                )
            )

    return errors 
Example #3
Source File: models.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def check(cls, **kwargs):
        """
        We use .session_key and CSRF_COOKIE above: check that they will be there, and fail fast if not.
        """
        errors = super().check(**kwargs)

        # Ensure we are using the database session store. (Other SessionStores may also have .session_key?)
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore
        if not issubclass(store, DatabaseSessionStore):
            errors.append(Error(
                "Quiz logging uses request.session.session_key, which likely implies "
                "SESSION_ENGINE = 'django.contrib.sessions.backends.db' in settings."
            ))

        if 'django.middleware.csrf.CsrfViewMiddleware' not in settings.MIDDLEWARE:
            errors.append(Error(
                "CsrfViewMiddleware is not enabled in settings: quiz logging uses CSRF_COOKIE and will fail without "
                "CSRF checking enabled. Also it should be enabled in general."
            ))

        return errors 
Example #4
Source File: checks.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def actions_have_consistent_hashes(app_configs, **kwargs):
    errors = []
    try:
        Action = apps.get_model("recipes", "Action")
        actions = list(Action.objects.filter(implementation__isnull=False))
    except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
        errors.append(Info(f"Could not retrieve actions: {e}", id=INFO_COULD_NOT_RETRIEVE_ACTIONS))
    else:
        for action in actions:
            if action.compute_implementation_hash() != action.implementation_hash:
                msg = "Action '{action}' (id={action.id}) has a mismatched hash".format(
                    action=action
                )
                errors.append(Error(msg, id=ERROR_MISMATCHED_ACTION_HASH))

    return errors 
Example #5
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def _check_column_name_clashes(cls):
        # Store a list of column names which have already been used by other fields.
        used_column_names = []
        errors = []

        for f in cls._meta.local_fields:
            _, column_name = f.get_attname_column()

            # Ensure the column name is not already in use.
            if column_name and column_name in used_column_names:
                errors.append(
                    checks.Error(
                        "Field '%s' has column name '%s' that is used by "
                        "another field." % (f.name, column_name),
                        hint="Specify a 'db_column' for the field.",
                        obj=cls,
                        id='models.E007'
                    )
                )
            else:
                used_column_names.append(column_name)

        return errors 
Example #6
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def _check_swappable(cls):
        """Check if the swapped model exists."""
        errors = []
        if cls._meta.swapped:
            try:
                apps.get_model(cls._meta.swapped)
            except ValueError:
                errors.append(
                    checks.Error(
                        "'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable,
                        id='models.E001',
                    )
                )
            except LookupError:
                app_label, model_name = cls._meta.swapped.split('.')
                errors.append(
                    checks.Error(
                        "'%s' references '%s.%s', which has not been "
                        "installed, or is abstract." % (
                            cls._meta.swappable, app_label, model_name
                        ),
                        id='models.E002',
                    )
                )
        return errors 
Example #7
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def _check_model_name_db_lookup_clashes(cls):
        errors = []
        model_name = cls.__name__
        if model_name.startswith('_') or model_name.endswith('_'):
            errors.append(
                checks.Error(
                    "The model name '%s' cannot start or end with an underscore "
                    "as it collides with the query lookup syntax." % model_name,
                    obj=cls,
                    id='models.E023'
                )
            )
        elif LOOKUP_SEP in model_name:
            errors.append(
                checks.Error(
                    "The model name '%s' cannot contain double underscores as "
                    "it collides with the query lookup syntax." % model_name,
                    obj=cls,
                    id='models.E024'
                )
            )
        return errors 
Example #8
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_column_name_clashes(cls):
        # Store a list of column names which have already been used by other fields.
        used_column_names = []
        errors = []

        for f in cls._meta.local_fields:
            _, column_name = f.get_attname_column()

            # Ensure the column name is not already in use.
            if column_name and column_name in used_column_names:
                errors.append(
                    checks.Error(
                        "Field '%s' has column name '%s' that is used by "
                        "another field." % (f.name, column_name),
                        hint="Specify a 'db_column' for the field.",
                        obj=cls,
                        id='models.E007'
                    )
                )
            else:
                used_column_names.append(column_name)

        return errors 
Example #9
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_referencing_to_swapped_model(self):
        if (self.rel.to not in apps.get_models() and
                not isinstance(self.rel.to, six.string_types) and
                self.rel.to._meta.swapped):
            model = "%s.%s" % (
                self.rel.to._meta.app_label,
                self.rel.to._meta.object_name
            )
            return [
                checks.Error(
                    ("Field defines a relation with the model '%s', "
                     "which has been swapped out.") % model,
                    hint="Update the relation to point at 'settings.%s'." % self.rel.to._meta.swappable,
                    obj=self,
                    id='fields.E301',
                )
            ]
        return [] 
Example #10
Source File: array.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def check(self, **kwargs):
        errors = super(ArrayField, self).check(**kwargs)
        if self.base_field.rel:
            errors.append(
                checks.Error(
                    'Base field for array cannot be a related field.',
                    hint=None,
                    obj=self,
                    id='postgres.E002'
                )
            )
        else:
            # Remove the field name checks as they are not needed here.
            base_errors = self.base_field.check()
            if base_errors:
                messages = '\n    '.join('%s (%s)' % (error.msg, error.id) for error in base_errors)
                errors.append(
                    checks.Error(
                        'Base field for array has errors:\n    %s' % messages,
                        hint=None,
                        obj=self,
                        id='postgres.E001'
                    )
                )
        return errors 
Example #11
Source File: options.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def check(cls, model, **kwargs):
        if cls.validator_class:
            warnings.warn(
                'ModelAdmin.validator_class is deprecated. '
                'ModelAdmin validators must be converted to use '
                'the system check framework.',
                RemovedInDjango19Warning)
            validator = cls.validator_class()
            try:
                validator.validate(cls, model)
            except ImproperlyConfigured as e:
                return [checks.Error(e.args[0], hint=None, obj=cls)]
            else:
                return []
        else:
            return cls.checks_class().check(cls, model, **kwargs) 
Example #12
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_null_allowed_for_primary_keys(self):
        if (self.primary_key and self.null and
                not connection.features.interprets_empty_strings_as_nulls):
            # We cannot reliably check this for backends like Oracle which
            # consider NULL and '' to be equal (and thus set up
            # character-based fields a little differently).
            return [
                checks.Error(
                    'Primary keys must not have null=True.',
                    hint=('Set null=False on the field, or '
                          'remove primary_key=True argument.'),
                    obj=self,
                    id='fields.E007',
                )
            ]
        else:
            return [] 
Example #13
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_max_length_attribute(self, **kwargs):
        try:
            max_length = int(self.max_length)
            if max_length <= 0:
                raise ValueError()
        except TypeError:
            return [
                checks.Error(
                    "CharFields must define a 'max_length' attribute.",
                    hint=None,
                    obj=self,
                    id='fields.E120',
                )
            ]
        except ValueError:
            return [
                checks.Error(
                    "'max_length' must be a positive integer.",
                    hint=None,
                    obj=self,
                    id='fields.E121',
                )
            ]
        else:
            return [] 
Example #14
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_mutually_exclusive_options(self):
        # auto_now, auto_now_add, and default are mutually exclusive
        # options. The use of more than one of these options together
        # will trigger an Error
        mutually_exclusive_options = [self.auto_now_add, self.auto_now,
                                      self.has_default()]
        enabled_options = [option not in (None, False)
                          for option in mutually_exclusive_options].count(True)
        if enabled_options > 1:
            return [
                checks.Error(
                    "The options auto_now, auto_now_add, and default "
                    "are mutually exclusive. Only one of these options "
                    "may be present.",
                    hint=None,
                    obj=self,
                    id='fields.E160',
                )
            ]
        else:
            return [] 
Example #15
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_decimal_places(self):
        try:
            decimal_places = int(self.decimal_places)
            if decimal_places < 0:
                raise ValueError()
        except TypeError:
            return [
                checks.Error(
                    "DecimalFields must define a 'decimal_places' attribute.",
                    hint=None,
                    obj=self,
                    id='fields.E130',
                )
            ]
        except ValueError:
            return [
                checks.Error(
                    "'decimal_places' must be a non-negative integer.",
                    hint=None,
                    obj=self,
                    id='fields.E131',
                )
            ]
        else:
            return [] 
Example #16
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_max_digits(self):
        try:
            max_digits = int(self.max_digits)
            if max_digits <= 0:
                raise ValueError()
        except TypeError:
            return [
                checks.Error(
                    "DecimalFields must define a 'max_digits' attribute.",
                    hint=None,
                    obj=self,
                    id='fields.E132',
                )
            ]
        except ValueError:
            return [
                checks.Error(
                    "'max_digits' must be a positive integer.",
                    hint=None,
                    obj=self,
                    id='fields.E133',
                )
            ]
        else:
            return [] 
Example #17
Source File: checks.py    From GTDWeb with 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 #18
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_radio_fields_value(self, cls, model, val, label):
        """ Check type of a value of `radio_fields` dictionary. """

        from django.contrib.admin.options import HORIZONTAL, VERTICAL

        if val not in (HORIZONTAL, VERTICAL):
            return [
                checks.Error(
                    "The value of '%s' must be either admin.HORIZONTAL or admin.VERTICAL." % label,
                    hint=None,
                    obj=cls,
                    id='admin.E024',
                )
            ]
        else:
            return [] 
Example #19
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_radio_fields_key(self, cls, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        try:
            field = model._meta.get_field(field_name)
        except FieldDoesNotExist:
            return refer_to_missing_field(field=field_name, option=label,
                                          model=model, obj=cls, id='admin.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
Example #20
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_exclude(self, cls, model):
        """ Check that exclude is a sequence without duplicates. """

        if cls.exclude is None:  # default value is None
            return []
        elif not isinstance(cls.exclude, (list, tuple)):
            return must_be('a list or tuple', option='exclude', obj=cls, id='admin.E014')
        elif len(cls.exclude) > len(set(cls.exclude)):
            return [
                checks.Error(
                    "The value of 'exclude' contains duplicate field(s).",
                    hint=None,
                    obj=cls,
                    id='admin.E015',
                )
            ]
        else:
            return [] 
Example #21
Source File: fields.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_generic_foreign_key_existence(self):
        target = self.rel.to
        if isinstance(target, ModelBase):
            # Using `vars` is very ugly approach, but there is no better one,
            # because GenericForeignKeys are not considered as fields and,
            # therefore, are not included in `target._meta.local_fields`.
            fields = target._meta.virtual_fields
            if any(isinstance(field, GenericForeignKey) and
                    field.ct_field == self.content_type_field_name and
                    field.fk_field == self.object_id_field_name
                    for field in fields):
                return []
            else:
                return [
                    checks.Error(
                        ("The GenericRelation defines a relation with the model "
                         "'%s.%s', but that model does not have a GenericForeignKey.") % (
                            target._meta.app_label, target._meta.object_name
                        ),
                        hint=None,
                        obj=self,
                        id='contenttypes.E004',
                    )
                ]
        else:
            return [] 
Example #22
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_exclude_of_parent_model(self, cls, parent_model):
        # Do not perform more specific checks if the base checks result in an
        # error.
        errors = super(InlineModelAdminChecks, self)._check_exclude(cls, parent_model)
        if errors:
            return []

        # Skip if `fk_name` is invalid.
        if self._check_relation(cls, parent_model):
            return []

        if cls.exclude is None:
            return []

        fk = _get_foreign_key(parent_model, cls.model, fk_name=cls.fk_name)
        if fk.name in cls.exclude:
            return [
                checks.Error(
                    "Cannot exclude the field '%s', because it is the foreign key "
                    "to the parent model '%s.%s'." % (
                        fk.name, parent_model._meta.app_label, parent_model._meta.object_name
                    ),
                    hint=None,
                    obj=cls,
                    id='admin.E201',
                )
            ]
        else:
            return [] 
Example #23
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _check_model(cls):
        errors = []
        if cls._meta.proxy:
            if cls._meta.local_fields or cls._meta.local_many_to_many:
                errors.append(
                    checks.Error(
                        "Proxy model '%s' contains model fields." % cls.__name__,
                        id='models.E017',
                    )
                )
        return errors 
Example #24
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _check_m2m_through_same_relationship(cls):
        """ Check if no relationship model is used by more than one m2m field.
        """

        errors = []
        seen_intermediary_signatures = []

        fields = cls._meta.local_many_to_many

        # Skip when the target model wasn't found.
        fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase))

        # Skip when the relationship model wasn't found.
        fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase))

        for f in fields:
            signature = (f.remote_field.model, cls, f.remote_field.through)
            if signature in seen_intermediary_signatures:
                errors.append(
                    checks.Error(
                        "The model has two many-to-many relations through "
                        "the intermediate model '%s'." % f.remote_field.through._meta.label,
                        obj=cls,
                        id='models.E003',
                    )
                )
            else:
                seen_intermediary_signatures.append(signature)
        return errors 
Example #25
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_inlines_item(self, cls, model, inline, label):
        """ Check one inline model admin. """
        inline_label = '.'.join([inline.__module__, inline.__name__])

        from django.contrib.admin.options import BaseModelAdmin

        if not issubclass(inline, BaseModelAdmin):
            return [
                checks.Error(
                    "'%s' must inherit from 'BaseModelAdmin'." % inline_label,
                    hint=None,
                    obj=cls,
                    id='admin.E104',
                )
            ]
        elif not inline.model:
            return [
                checks.Error(
                    "'%s' must have a 'model' attribute." % inline_label,
                    hint=None,
                    obj=cls,
                    id='admin.E105',
                )
            ]
        elif not issubclass(inline.model, models.Model):
            return must_be('a Model', option='%s.model' % inline_label,
                           obj=cls, id='admin.E106')
        else:
            return inline.check(model) 
Example #26
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def _check_id_field(cls):
        """Check if `id` field is a primary key."""
        fields = [f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk]
        # fields is empty or consists of the invalid "id" field
        if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
            return [
                checks.Error(
                    "'id' can only be used as a field name if the field also "
                    "sets 'primary_key=True'.",
                    obj=cls,
                    id='models.E004',
                )
            ]
        else:
            return [] 
Example #27
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_ordering_item(self, cls, model, field_name, label):
        """ Check that `ordering` refers to existing fields. """

        if field_name == '?' and len(cls.ordering) != 1:
            return [
                checks.Error(
                    ("The value of 'ordering' has the random ordering marker '?', "
                     "but contains other fields as well."),
                    hint='Either remove the "?", or remove the other fields.',
                    obj=cls,
                    id='admin.E032',
                )
            ]
        elif field_name == '?':
            return []
        elif '__' in field_name:
            # Skip ordering in the format field1__field2 (FIXME: checking
            # this format would be nice, but it's a little fiddly).
            return []
        else:
            if field_name.startswith('-'):
                field_name = field_name[1:]

            try:
                model._meta.get_field(field_name)
            except FieldDoesNotExist:
                return refer_to_missing_field(field=field_name, option=label,
                                              model=model, obj=cls, id='admin.E033')
            else:
                return [] 
Example #28
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_prepopulated_fields_key(self, cls, 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.
        """

        forbidden_field_types = (
            models.DateTimeField,
            models.ForeignKey,
            models.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.E027')
        else:
            if isinstance(field, forbidden_field_types):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which must not be a DateTimeField, "
                        "ForeignKey or ManyToManyField." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E028',
                    )
                ]
            else:
                return [] 
Example #29
Source File: fields.py    From django-osm-field with MIT License 5 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 #30
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_fieldsets_item(self, cls, model, fieldset, label):
        """ Check an item of `fieldsets`, i.e. check that this is a pair of a
        set name and a dictionary containing "fields" key. """

        if not isinstance(fieldset, (list, tuple)):
            return must_be('a list or tuple', option=label, obj=cls, id='admin.E008')
        elif len(fieldset) != 2:
            return must_be('of length 2', option=label, obj=cls, id='admin.E009')
        elif not isinstance(fieldset[1], dict):
            return must_be('a dictionary', option='%s[1]' % label, obj=cls, id='admin.E010')
        elif 'fields' not in fieldset[1]:
            return [
                checks.Error(
                    "The value of '%s[1]' must contain the key 'fields'." % label,
                    hint=None,
                    obj=cls,
                    id='admin.E011',
                )
            ]
        elif not isinstance(fieldset[1]['fields'], (list, tuple)):
            return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=cls, id='admin.E008')

        fields = flatten(fieldset[1]['fields'])
        if len(fields) != len(set(fields)):
            return [
                checks.Error(
                    "There are duplicate field(s) in '%s[1]'." % label,
                    hint=None,
                    obj=cls,
                    id='admin.E012',
                )
            ]
        return list(chain(*[
            self._check_field_spec(cls, model, fieldset_fields, '%s[1]["fields"]' % label)
            for fieldset_fields in fieldset[1]['fields']
        ]))