我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.checks.Error()。
def _check_generic_foreign_key_existence(self): target = self.remote_field.model if isinstance(target, ModelBase): 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 []
def check(self, **kwargs): errors = super(ArrayField, self).check(**kwargs) if self.base_field.remote_field: 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
def _check_exclude(self, obj): """ Check that exclude is a sequence without duplicates. """ if obj.exclude is None: # default value is None return [] elif not isinstance(obj.exclude, (list, tuple)): return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014') elif len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", hint=None, obj=obj.__class__, id='admin.E015', ) ] else: return []
def _check_radio_fields_value(self, obj, 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=obj.__class__, id='admin.E024', ) ] else: return []
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 ), hint=None, obj=obj.__class__, id='admin.E035', ) ] else: return []
def _check_referencing_to_swapped_model(self): if (self.remote_field.model not in self.opts.apps.get_models() and not isinstance(self.remote_field.model, six.string_types) and self.remote_field.model._meta.swapped): model = "%s.%s" % ( self.remote_field.model._meta.app_label, self.remote_field.model._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.remote_field.model._meta.swappable, obj=self, id='fields.E301', ) ] return []
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 []
def _check_max_length_attribute(self, **kwargs): if self.max_length is None: return [ checks.Error( "CharFields must define a 'max_length' attribute.", hint=None, obj=self, id='fields.E120', ) ] elif not isinstance(self.max_length, six.integer_types) or self.max_length <= 0: return [ checks.Error( "'max_length' must be a positive integer.", hint=None, obj=self, id='fields.E121', ) ] else: return []
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 []
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 []
def _check_id_field(cls): """ Check if `id` field is a primary key. """ fields = list(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'.", hint=None, obj=cls, id='models.E004', ) ] else: return []
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
def check_mandatory_apps_are_in_installed_apps(app_configs, **kwargs): from django.conf import settings errors = [] needed_modules = [ 'corsheaders', 'elokenz_twote', 'rest_framework', ] for module in needed_modules: if module not in settings.INSTALLED_APPS: errors.append( Error( 'INSTALLED_APPS is incomplete', hint="Add '{mod}' in your INSTALLED_APPS".format( mod=module), obj='Import Error', id='contact_form.check', ) ) return errors
def check_all_models(app_configs=None, **kwargs): errors = [] if app_configs is None: models = apps.get_models() else: models = chain.from_iterable(app_config.get_models() for app_config in app_configs) for model in models: if not inspect.ismethod(model.check): errors.append( Error( "The '%s.check()' class method is currently overridden by %r." % (model.__name__, model.check), obj=model, id='models.E020' ) ) else: errors.extend(model.check(**kwargs)) return errors
def _check_generic_foreign_key_existence(self): target = self.remote_field.model if isinstance(target, ModelBase): fields = target._meta.private_fields if any(self._is_matching_generic_foreign_key(field) 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 ), obj=self, id='contenttypes.E004', ) ] else: return []
def _check_field_name(self): field_name = self._get_field_name() try: field = self.model._meta.get_field(field_name) except FieldDoesNotExist: return [ checks.Error( "CurrentSiteManager could not find a field named '%s'." % field_name, obj=self, id='sites.E001', ) ] if not field.many_to_many and not isinstance(field, (models.ForeignKey)): return [ checks.Error( "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key or a many-to-many field." % ( self.model._meta.object_name, field_name ), obj=self, id='sites.E002', ) ] return []
def check(self, **kwargs): errors = super(ArrayField, self).check(**kwargs) if self.base_field.remote_field: errors.append( checks.Error( 'Base field for array cannot be a related field.', 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, obj=self, id='postgres.E001' ) ) return errors
def _check_exclude(self, obj): """ Check that exclude is a sequence without duplicates. """ if obj.exclude is None: # default value is None return [] elif not isinstance(obj.exclude, (list, tuple)): return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014') elif len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", obj=obj.__class__, id='admin.E015', ) ] else: return []
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 []
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, or a ManyToManyField." % (label, field_name), obj=obj.__class__, id='admin.E028', ) ] else: return []
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 []
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 []
def _check_date_hierarchy(self, obj): """ Check that date_hierarchy refers to DateField or DateTimeField. """ if obj.date_hierarchy is None: return [] else: try: field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of 'date_hierarchy' refers to '%s', which " "does not refer to a Field." % obj.date_hierarchy, obj=obj.__class__, id='admin.E127', ) ] else: if not isinstance(field, (models.DateField, models.DateTimeField)): return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') else: return []
def check_gstorage_params(**kwargs): """ Check that the module is initialized with all the required settings/environment Args: kwargs: optional list of app_config Returns: A list of errors """ errors = [] module_name = 'gstorage' for index, field in enumerate(REQUIRED_SETTINGS): if not get_config(field): errors.append( checks.Error( '%s is required' % field, hint=None, obj=module_name, id='%s.00%s' % (module_name, index + 1) # use 1-based index for errors ) ) return errors
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
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
def check_database_connected(app_configs, **kwargs): """ A Django check to see if connecting to the configured default database backend succeeds. """ errors = [] try: connection.ensure_connection() except OperationalError as e: msg = 'Could not connect to database: {!s}'.format(e) errors.append(checks.Error(msg, id=ERROR_CANNOT_CONNECT_DATABASE)) except ImproperlyConfigured as e: msg = 'Datbase misconfigured: "{!s}"'.format(e) errors.append(checks.Error(msg, id=ERROR_MISCONFIGURED_DATABASE)) else: if not connection.is_usable(): errors.append(checks.Error('Database connection is not usable', id=ERROR_UNUSABLE_DATABASE)) return errors
def _check_options(self, **kwargs): if not self.editor_options: return [ checks.Error( 'options required', obj=self ) ] elif not isinstance(self.editor_options, dict): return [ checks.Error( 'options must be a dict', obj=self ) ] else: return []
def _check_storage_location(cls, **kwargs): if not cls.STORAGE_LOCATION: return [ checks.Error( 'STORAGE_LOCATION is required', obj=cls ) ] elif not isinstance(cls.STORAGE_LOCATION, str): return [ checks.Error( 'STORAGE_LOCATION must be an instance of str', obj=cls ) ] else: return []
def _check_max_dimensions(cls, **kwargs): if not cls.MAX_DIMENSIONS: return [ checks.Error( 'MAX_DIMENSIONS is required', obj=cls ) ] elif not is_size(cls.MAX_DIMENSIONS): return [ checks.Error( 'MAX_DIMENSIONS must be a tuple of 2 non-negative numbers', obj=cls ) ] else: return []
def _check_max_source_dimensions(cls, **kwargs): if not cls.MAX_SOURCE_DIMENSIONS: return [ checks.Error( 'MAX_SOURCE_DIMENSIONS is required', obj=cls ) ] elif not is_size(cls.MAX_SOURCE_DIMENSIONS): return [ checks.Error( 'MAX_SOURCE_DIMENSIONS must be a tuple of 2 non-negative numbers', obj=cls ) ] else: return []
def _check_variations(cls, **kwargs): if not cls.VARIATIONS: return [ checks.Error( 'VARIATIONS is required', obj=cls ) ] elif not isinstance(cls.VARIATIONS, dict): return [ checks.Error( 'VARIATIONS must be an instance of dict', obj=cls ) ] errors = [] errors.extend(check_variations(cls.VARIATIONS, cls)) return errors
def _check_admin_variation(cls, **kwargs): if not cls.ADMIN_VARIATION: return [ checks.Error( 'ADMIN_VARIATION is required', obj=cls ) ] elif cls.ADMIN_VARIATION not in cls.VARIATIONS: return [ checks.Error( 'ADMIN_VARIATION "%s" not found in variations' % cls.admin_variation, obj=cls ) ] else: return []
def _check_admin_item_size(cls, **kwargs): if not cls.ADMIN_ITEM_SIZE: return [ checks.Error( 'ADMIN_ITEM_SIZE is required', obj=cls ) ] elif not is_size(cls.ADMIN_ITEM_SIZE): return [ checks.Error( 'ADMIN_ITEM_SIZE should be a tuple of 2 non-negative numbers', obj=cls ) ] else: return []
def recut_generator(self): """ ????????? ??????????? ???? ???????? ???????. ??????: for error_code, msg in gallery.recut_generator(): print(msg) if error_code: break """ image_items = list(self.image_items) for item in image_items: if not item.image: yield 1, 'Error (ID %d): Empty value' % item.pk continue if not item.image.exists(): yield 2, 'Error (ID %d): Not found %r' % (item.pk, item.image.url) continue item.image.recut() yield 0, item.image.url