Here are the examples of the python api django.core.checks.Error taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
141 Examples
0
Example 101
Project: cgstudiomap Source File: checks.py
def _check_fields(self, obj):
""" Check that `fields` only refer to existing fields, doesn't contain
duplicates. Check if at most one of `fields` and `fieldsets` is defined.
"""
if obj.fields is None:
return []
elif not isinstance(obj.fields, (list, tuple)):
return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004')
elif obj.fieldsets:
return [
checks.Error(
"Both 'fieldsets' and 'fields' are specified.",
hint=None,
obj=obj.__class__,
id='admin.E005',
)
]
fields = flatten(obj.fields)
if len(fields) != len(set(fields)):
return [
checks.Error(
"The value of 'fields' contains duplicate field(s).",
hint=None,
obj=obj.__class__,
id='admin.E006',
)
]
return list(chain(*[
self._check_field_spec(obj, obj.model, field_name, 'fields')
for field_name in obj.fields
]))
0
Example 102
Project: cgstudiomap Source File: checks.py
def _check_fieldsets_item(self, obj, 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=obj, id='admin.E008')
elif len(fieldset) != 2:
return must_be('of length 2', option=label, obj=obj, id='admin.E009')
elif not isinstance(fieldset[1], dict):
return must_be('a dictionary', option='%s[1]' % label, obj=obj, 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=obj.__class__,
id='admin.E011',
)
]
elif not isinstance(fieldset[1]['fields'], (list, tuple)):
return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, 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=obj.__class__,
id='admin.E012',
)
]
return list(chain(*[
self._check_field_spec(obj, model, fieldset_fields, '%s[1]["fields"]' % label)
for fieldset_fields in fieldset[1]['fields']
]))
0
Example 103
Project: cgstudiomap Source File: checks.py
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.
"""
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=obj, 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=obj.__class__,
id='admin.E028',
)
]
else:
return []
0
Example 104
Project: cgstudiomap Source File: checks.py
def _check_list_display_item(self, obj, model, item, label):
if callable(item):
return []
elif hasattr(obj, item):
return []
elif hasattr(model, item):
# getattr(model, item) could be an X_RelatedObjectsDescriptor
try:
field = model._meta.get_field(item)
except FieldDoesNotExist:
try:
field = getattr(model, item)
except AttributeError:
field = None
if field is None:
return [
checks.Error(
"The value of '%s' refers to '%s', which is not a "
"callable, an attribute of '%s', or an attribute or method on '%s.%s'." % (
label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
),
hint=None,
obj=obj.__class__,
id='admin.E108',
)
]
elif isinstance(field, models.ManyToManyField):
return [
checks.Error(
"The value of '%s' must not be a ManyToManyField." % label,
hint=None,
obj=obj.__class__,
id='admin.E109',
)
]
else:
return []
else:
try:
model._meta.get_field(item)
except FieldDoesNotExist:
return [
# This is a deliberate repeat of E108; there's more than one path
# required to test this condition.
checks.Error(
"The value of '%s' refers to '%s', which is not a callable, "
"an attribute of '%s', or an attribute or method on '%s.%s'." % (
label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
),
hint=None,
obj=obj.__class__,
id='admin.E108',
)
]
else:
return []
0
Example 105
Project: cgstudiomap Source File: checks.py
def _check_list_filter_item(self, obj, model, item, label):
"""
Check one item of `list_filter`, i.e. check if it is one of three options:
1. 'field' -- a basic field filter, possibly w/ relationships (e.g.
'field__rel')
2. ('field', SomeFieldListFilter) - a field-based list filter class
3. SomeListFilter - a non-field list filter class
"""
from django.contrib.admin import ListFilter, FieldListFilter
if callable(item) and not isinstance(item, models.Field):
# If item is option 3, it should be a ListFilter...
if not issubclass(item, ListFilter):
return must_inherit_from(parent='ListFilter', option=label,
obj=obj, id='admin.E113')
# ... but not a FieldListFilter.
elif issubclass(item, FieldListFilter):
return [
checks.Error(
"The value of '%s' must not inherit from 'FieldListFilter'." % label,
hint=None,
obj=obj.__class__,
id='admin.E114',
)
]
else:
return []
elif isinstance(item, (tuple, list)):
# item is option #2
field, list_filter_class = item
if not issubclass(list_filter_class, FieldListFilter):
return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label,
obj=obj, id='admin.E115')
else:
return []
else:
# item is option #1
field = item
# Validate the field string
try:
get_fields_from_path(model, field)
except (NotRelationField, FieldDoesNotExist):
return [
checks.Error(
"The value of '%s' refers to '%s', which does not refer to a Field." % (label, field),
hint=None,
obj=obj.__class__,
id='admin.E116',
)
]
else:
return []
0
Example 106
def _check_list_editable_item(self, obj, model, field_name, label):
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.E121')
else:
if field_name not in obj.list_display:
return [
checks.Error(
"The value of '%s' refers to '%s', which is not "
"contained in 'list_display'." % (label, field_name),
hint=None,
obj=obj.__class__,
id='admin.E122',
)
]
elif obj.list_display_links and field_name in obj.list_display_links:
return [
checks.Error(
"The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name,
hint=None,
obj=obj.__class__,
id='admin.E123',
)
]
# Check that list_display_links is set, and that the first values of list_editable and list_display are
# not the same. See ticket #22792 for the use case relating to this.
elif (obj.list_display[0] in obj.list_editable and obj.list_display[0] != obj.list_editable[0] and
obj.list_display_links is not None):
return [
checks.Error(
"The value of '%s' refers to the first field in 'list_display' ('%s'), "
"which cannot be used unless 'list_display_links' is set." % (
label, obj.list_display[0]
),
hint=None,
obj=obj.__class__,
id='admin.E124',
)
]
elif not field.editable:
return [
checks.Error(
"The value of '%s' refers to '%s', which is not editable through the admin." % (
label, field_name
),
hint=None,
obj=obj.__class__,
id='admin.E125',
)
]
else:
return []
0
Example 107
Project: cgstudiomap Source File: checks.py
def check_user_model(**kwargs):
errors = []
cls = apps.get_model(settings.AUTH_USER_MODEL)
# Check that REQUIRED_FIELDS is a list
if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)):
errors.append(
checks.Error(
"'REQUIRED_FIELDS' must be a list or tuple.",
hint=None,
obj=cls,
id='auth.E001',
)
)
# Check that the USERNAME FIELD isn't included in REQUIRED_FIELDS.
if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS:
errors.append(
checks.Error(
("The field named as the 'USERNAME_FIELD' "
"for a custom user model must not be included in 'REQUIRED_FIELDS'."),
hint=None,
obj=cls,
id='auth.E002',
)
)
# Check that the username field is unique
if not cls._meta.get_field(cls.USERNAME_FIELD).unique:
if (settings.AUTHENTICATION_BACKENDS ==
['django.contrib.auth.backends.ModelBackend']):
errors.append(
checks.Error(
"'%s.%s' must be unique because it is named as the 'USERNAME_FIELD'." % (
cls._meta.object_name, cls.USERNAME_FIELD
),
hint=None,
obj=cls,
id='auth.E003',
)
)
else:
errors.append(
checks.Warning(
"'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique." % (
cls._meta.object_name, cls.USERNAME_FIELD
),
hint=('Ensure that your authentication backend(s) can handle '
'non-unique usernames.'),
obj=cls,
id='auth.W004',
)
)
return errors
0
Example 108
def _check_relation(self, obj, parent_model):
# There's no FK, but we do need to confirm that the ct_field and ct_fk_field are valid,
# and that they are part of a GenericForeignKey.
gfks = [
f for f in obj.model._meta.virtual_fields
if isinstance(f, GenericForeignKey)
]
if len(gfks) == 0:
return [
checks.Error(
"'%s.%s' has no GenericForeignKey." % (
obj.model._meta.app_label, obj.model._meta.object_name
),
hint=None,
obj=obj.__class__,
id='admin.E301'
)
]
else:
# Check that the ct_field and ct_fk_fields exist
try:
obj.model._meta.get_field(obj.ct_field)
except FieldDoesNotExist:
return [
checks.Error(
"'ct_field' references '%s', which is not a field on '%s.%s'." % (
obj.ct_field, obj.model._meta.app_label, obj.model._meta.object_name
),
hint=None,
obj=obj.__class__,
id='admin.E302'
)
]
try:
obj.model._meta.get_field(obj.ct_fk_field)
except FieldDoesNotExist:
return [
checks.Error(
"'ct_fk_field' references '%s', which is not a field on '%s.%s'." % (
obj.ct_fk_field, obj.model._meta.app_label, obj.model._meta.object_name
),
hint=None,
obj=obj.__class__,
id='admin.E303'
)
]
# There's one or more GenericForeignKeys; make sure that one of them
# uses the right ct_field and ct_fk_field.
for gfk in gfks:
if gfk.ct_field == obj.ct_field and gfk.fk_field == obj.ct_fk_field:
return []
return [
checks.Error(
"'%s.%s' has no GenericForeignKey using content type field '%s' and object ID field '%s'." % (
obj.model._meta.app_label, obj.model._meta.object_name, obj.ct_field, obj.ct_fk_field
),
hint=None,
obj=obj.__class__,
id='admin.E304'
)
]
0
Example 109
Project: cgstudiomap Source File: fields.py
def _check_content_type_field(self):
"""
Check if field named `field_name` in model `model` exists and is a
valid content_type field (is a ForeignKey to ContentType).
"""
try:
field = self.model._meta.get_field(self.ct_field)
except FieldDoesNotExist:
return [
checks.Error(
"The GenericForeignKey content type references the non-existent field '%s.%s'." % (
self.model._meta.object_name, self.ct_field
),
hint=None,
obj=self,
id='contenttypes.E002',
)
]
else:
if not isinstance(field, models.ForeignKey):
return [
checks.Error(
"'%s.%s' is not a ForeignKey." % (
self.model._meta.object_name, self.ct_field
),
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=self,
id='contenttypes.E003',
)
]
elif field.remote_field.model != ContentType:
return [
checks.Error(
"'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % (
self.model._meta.object_name, self.ct_field
),
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=self,
id='contenttypes.E004',
)
]
else:
return []
0
Example 110
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,
hint=None,
obj=self,
id='sites.E001',
)
]
if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
return [
checks.Error(
"CurrentSiteManager cannot use '%s.%s' as it is not a ForeignKey or ManyToManyField." % (
self.model._meta.object_name, field_name
),
hint=None,
obj=self,
id='sites.E002',
)
]
return []
0
Example 111
def check_field(self, field, **kwargs):
"""
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.
"""
from django.db import connection
errors = super(DatabaseValidation, self).check_field(field, **kwargs)
# Ignore any related fields.
if getattr(field, 'remote_field', None) is None:
field_type = field.db_type(connection)
# Ignore any non-concrete fields
if field_type is None:
return errors
if (field_type.startswith('varchar') # Look for CharFields...
and field.unique # ... that are unique
and (field.max_length is None or int(field.max_length) > 255)):
errors.append(
checks.Error(
('MySQL does not allow unique CharFields to have a max_length > 255.'),
hint=None,
obj=field,
id='mysql.E001',
)
)
return errors
0
Example 112
Project: django-sellmo Source File: execution.py
def compile(self, signature, provided=None):
# Make sure we are actually deadling with something callable
if not callable(self._func):
self.errors.append(Error("Must be callable", obj=self))
return False
self.is_generator = inspect.isgeneratorfunction(self._func)
# Parse args
argspec = inspect.getargspec(self._func)
args, required_args, bind_arg, result_arg = _parse_argspec(
argspec,
binds=self.binds,
takes_result=self.takes_result)
self.args = args
self.required_args = required_args
self.signature = signature
self.provided = list(provided or [])
self.errors = []
# Ensure func accepts kwargs
if argspec[2] is None:
self.errors.append(Error("Must accept **kwargs", obj=self))
return False
# Do extenive arg checks
success = True
# Collect reserverd args
offset = 0
reserved_args = []
if self.binds:
offset += 1
reserved_args.append(bind_arg)
if self.takes_result:
offset += 1
reserved_args.append(result_arg)
runtime_args = self.provided + self.signature.args
for arg in reserved_args:
if arg in runtime_args:
self.errors.append(
Error(
"Reserved argument '%s' "
"conflicts with a runtime "
"argument" % (arg, ),
obj=self
)
)
success = False
if not self is signature:
# Make sure the given func is either a regular function
# or a bound instance method.
if (isinstance(self._func, types.FunctionType) and
self.binds and not inspect.ismethod(self._func)):
self.errors.append(Error("Method is unbound", obj=self))
success = False
remaining_args = list(self.required_args)
if self.signature.binds:
# We require the arg
if not remaining_args:
self.errors.append(
Error(
"Signature is bound, need a first argument",
obj=self
)
)
success = False
elif remaining_args[0] in runtime_args:
self.errors.append(
Error(
"Reserved argument '%s' "
"conflicts with a runtime "
"argument" % (remaining_args[0], ),
obj=self
)
)
success = False
else:
remaining_args = remaining_args[1:]
for idx, arg in enumerate(remaining_args):
# Actual argument position
pos = idx + offset + 1
if not (arg in self.provided or arg in self.signature.args):
# Make sure the given func doesnt define any unassigned
# arguments
self.errors.append(
Error(
"Argument '%s' at position %s needs a default "
"value (%s)" % (arg, pos, self.provided ),
obj=self
)
)
success = False
if success:
functools.update_wrapper(self, self._func)
return success
0
Example 113
def check(self, **kwargs):
errors = super(RGBColorField, self).check(**kwargs)
if self.colors is not None:
if not isinstance(self.colors, (list, tuple)):
errors.append(Error(
'colors is not iterable',
hint='Define the colors param as list of strings.',
obj=self,
id='colorful.E001'
))
else:
try:
for color in self.colors:
self.clean(color, None)
except ValidationError:
errors.append(Error(
'colors item validation error',
hint='Each item of the colors param must be a valid '
'color string itself.',
obj=self,
id='colorful.E002'
))
return errors
0
Example 114
@patch('django.db.models.CharField.check')
def test_check(self, charfield_check):
test_apps = Apps()
# do not test django's charfield checks
charfield_check.side_effect = list
# fine fields from setUp
self.assertEqual(self.field.check(), [])
self.assertEqual(self.field_with_colors.check(), [])
# check type error
class ColorsTypeSystemCheckTestModel(models.Model):
color = RGBColorField(colors='#333,#ff00FF')
class Meta:
apps = test_apps
app_label = 'colorful'
self.assertEqual(ColorsTypeSystemCheckTestModel.check(), [
Error(
'colors is not iterable',
hint='Define the colors param as list of strings.',
obj=ColorsTypeSystemCheckTestModel._meta.get_field('color'),
id='colorful.E001'
)
])
# check item error
class ColorsItemSystemCheckTestModel(models.Model):
color = RGBColorField(colors=['#'])
class Meta:
apps = test_apps
app_label = 'colorful'
self.assertEqual(ColorsItemSystemCheckTestModel.check(), [
Error(
'colors item validation error',
hint='Each item of the colors param must be a valid color '
'string itself.',
obj=ColorsItemSystemCheckTestModel._meta.get_field('color'),
id='colorful.E002'
)
])
0
Example 115
@classmethod
def check(cls, **kwargs):
errors = super(BasePolymorphicModel, cls).check(**kwargs)
try:
content_type_field_name = getattr(cls, 'CONTENT_TYPE_FIELD')
except AttributeError:
errors.append(checks.Error(
'`BasePolymorphicModel` subclasses must define a `CONTENT_TYPE_FIELD`.',
hint=None,
obj=cls,
id='polymodels.E001',
))
else:
try:
content_type_field = cls._meta.get_field(content_type_field_name)
except FieldDoesNotExist:
errors.append(checks.Error(
"`CONTENT_TYPE_FIELD` points to an inexistent field '%s'." % content_type_field_name,
hint=None,
obj=cls,
id='polymodels.E002',
))
else:
if (not isinstance(content_type_field, models.ForeignKey) or
get_remote_model(get_remote_field(content_type_field)) is not ContentType):
errors.append(checks.Error(
"`%s` must be a `ForeignKey` to `ContentType`." % content_type_field_name,
hint=None,
obj=content_type_field,
id='polymodels.E003',
))
return errors
0
Example 116
Project: django-polymodels Source File: test_fields.py
def test_checks(self):
test_apps = Apps(['tests', 'django.contrib.contenttypes'])
class ContentType(models.Model):
class Meta:
apps = test_apps
app_label = 'contenttypes'
class CheckModel(PolymorphicModel):
valid = PolymorphicTypeField('self', on_delete=models.CASCADE)
unresolved = PolymorphicTypeField('unresolved', on_delete=models.CASCADE)
non_polymorphic_base = PolymorphicTypeField('contenttypes.ContentType', on_delete=models.CASCADE)
class Meta:
apps = test_apps
def assert_checks_equal(field, errors):
# TODO: Remove when dropping support for Django 1.8.
if django.VERSION < (1, 9):
errors.insert(0, checks.Error(
"Field defines a relation with model 'ContentType', "
"which is either not installed, or is abstract.",
id='fields.E300',
obj=field,
))
self.assertEqual(field.check(), errors)
assert_checks_equal(CheckModel._meta.get_field('valid'), [])
assert_checks_equal(CheckModel._meta.get_field('unresolved'), [
checks.Error(
"Field defines a relation with model 'unresolved', which is either not installed, or is abstract.",
id='fields.E300',
),
])
assert_checks_equal(CheckModel._meta.get_field('non_polymorphic_base'), [
checks.Error(
"The ContentType type is not a subclass of BasePolymorphicModel.",
id='polymodels.E004',
),
])
0
Example 117
def test_checks(self):
test_apps = Apps()
options = type(str('Meta'), (), {'apps': test_apps, 'app_label': 'polymodels'})
class NoCtFieldModel(BasePolymorphicModel):
Meta = options
self.assertIn(checks.Error(
'`BasePolymorphicModel` subclasses must define a `CONTENT_TYPE_FIELD`.',
hint=None,
obj=NoCtFieldModel,
id='polymodels.E001',
), NoCtFieldModel.check())
class InexistentCtFieldModel(BasePolymorphicModel):
CONTENT_TYPE_FIELD = 'inexistent_field'
Meta = options
self.assertIn(checks.Error(
"`CONTENT_TYPE_FIELD` points to an inexistent field 'inexistent_field'.",
hint=None,
obj=InexistentCtFieldModel,
id='polymodels.E002',
), InexistentCtFieldModel.check())
class InvalidCtFieldModel(BasePolymorphicModel):
CONTENT_TYPE_FIELD = 'a_char_field'
a_char_field = models.CharField(max_length=255)
Meta = options
self.assertIn(checks.Error(
"`a_char_field` must be a `ForeignKey` to `ContentType`.",
hint=None,
obj=InvalidCtFieldModel._meta.get_field('a_char_field'),
id='polymodels.E003',
), InvalidCtFieldModel.check())
class InvalidCtFkFieldToModel(BasePolymorphicModel):
CONTENT_TYPE_FIELD = 'a_fk'
a_fk = models.ForeignKey('self', on_delete=models.CASCADE)
Meta = options
self.assertIn(checks.Error(
"`a_fk` must be a `ForeignKey` to `ContentType`.",
hint=None,
obj=InvalidCtFkFieldToModel._meta.get_field('a_fk'),
id='polymodels.E003',
), InvalidCtFkFieldToModel.check())
0
Example 118
Project: django Source File: checks.py
def check_dependencies(**kwargs):
"""
Check that the admin's dependencies are correctly installed.
"""
errors = []
# contrib.contenttypes must be installed.
if not apps.is_installed('django.contrib.contenttypes'):
missing_app = checks.Error(
"'django.contrib.contenttypes' must be in INSTALLED_APPS in order "
"to use the admin application.",
id="admin.E401",
)
errors.append(missing_app)
# The auth context processor must be installed if using the default
# authentication backend.
try:
default_template_engine = Engine.get_default()
except Exception:
# Skip this non-critical check:
# 1. if the user has a non-trivial TEMPLATES setting and Django
# can't find a default template engine
# 2. if anything goes wrong while loading template engines, in
# order to avoid raising an exception from a confusing location
# Catching ImproperlyConfigured suffices for 1. but 2. requires
# catching all exceptions.
pass
else:
if ('django.contrib.auth.context_processors.auth'
not in default_template_engine.context_processors and
'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS):
missing_template = checks.Error(
"'django.contrib.auth.context_processors.auth' must be in "
"TEMPLATES in order to use the admin application.",
id="admin.E402"
)
errors.append(missing_template)
return errors
0
Example 119
Project: django Source File: checks.py
def _check_fields(self, obj):
""" Check that `fields` only refer to existing fields, doesn't contain
duplicates. Check if at most one of `fields` and `fieldsets` is defined.
"""
if obj.fields is None:
return []
elif not isinstance(obj.fields, (list, tuple)):
return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004')
elif obj.fieldsets:
return [
checks.Error(
"Both 'fieldsets' and 'fields' are specified.",
obj=obj.__class__,
id='admin.E005',
)
]
fields = flatten(obj.fields)
if len(fields) != len(set(fields)):
return [
checks.Error(
"The value of 'fields' contains duplicate field(s).",
obj=obj.__class__,
id='admin.E006',
)
]
return list(chain(*[
self._check_field_spec(obj, obj.model, field_name, 'fields')
for field_name in obj.fields
]))
0
Example 120
Project: django Source File: checks.py
def _check_fieldsets_item(self, obj, 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=obj, id='admin.E008')
elif len(fieldset) != 2:
return must_be('of length 2', option=label, obj=obj, id='admin.E009')
elif not isinstance(fieldset[1], dict):
return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010')
elif 'fields' not in fieldset[1]:
return [
checks.Error(
"The value of '%s[1]' must contain the key 'fields'." % label,
obj=obj.__class__,
id='admin.E011',
)
]
elif not isinstance(fieldset[1]['fields'], (list, tuple)):
return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, 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,
obj=obj.__class__,
id='admin.E012',
)
]
return list(chain(*[
self._check_field_spec(obj, model, fieldset_fields, '%s[1]["fields"]' % label)
for fieldset_fields in fieldset[1]['fields']
]))
0
Example 121
Project: django Source File: checks.py
def _check_list_display_item(self, obj, model, item, label):
if callable(item):
return []
elif hasattr(obj, item):
return []
elif hasattr(model, item):
# getattr(model, item) could be an X_RelatedObjectsDescriptor
try:
field = model._meta.get_field(item)
except FieldDoesNotExist:
try:
field = getattr(model, item)
except AttributeError:
field = None
if field is None:
return [
checks.Error(
"The value of '%s' refers to '%s', which is not a "
"callable, an attribute of '%s', or an attribute or method on '%s.%s'." % (
label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
),
obj=obj.__class__,
id='admin.E108',
)
]
elif isinstance(field, models.ManyToManyField):
return [
checks.Error(
"The value of '%s' must not be a ManyToManyField." % label,
obj=obj.__class__,
id='admin.E109',
)
]
else:
return []
else:
try:
model._meta.get_field(item)
except FieldDoesNotExist:
return [
# This is a deliberate repeat of E108; there's more than one path
# required to test this condition.
checks.Error(
"The value of '%s' refers to '%s', which is not a callable, "
"an attribute of '%s', or an attribute or method on '%s.%s'." % (
label, item, obj.__class__.__name__, model._meta.app_label, model._meta.object_name
),
obj=obj.__class__,
id='admin.E108',
)
]
else:
return []
0
Example 122
Project: django Source File: checks.py
def _check_list_filter_item(self, obj, model, item, label):
"""
Check one item of `list_filter`, i.e. check if it is one of three options:
1. 'field' -- a basic field filter, possibly w/ relationships (e.g.
'field__rel')
2. ('field', SomeFieldListFilter) - a field-based list filter class
3. SomeListFilter - a non-field list filter class
"""
from django.contrib.admin import ListFilter, FieldListFilter
if callable(item) and not isinstance(item, models.Field):
# If item is option 3, it should be a ListFilter...
if not issubclass(item, ListFilter):
return must_inherit_from(parent='ListFilter', option=label,
obj=obj, id='admin.E113')
# ... but not a FieldListFilter.
elif issubclass(item, FieldListFilter):
return [
checks.Error(
"The value of '%s' must not inherit from 'FieldListFilter'." % label,
obj=obj.__class__,
id='admin.E114',
)
]
else:
return []
elif isinstance(item, (tuple, list)):
# item is option #2
field, list_filter_class = item
if not issubclass(list_filter_class, FieldListFilter):
return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115')
else:
return []
else:
# item is option #1
field = item
# Validate the field string
try:
get_fields_from_path(model, field)
except (NotRelationField, FieldDoesNotExist):
return [
checks.Error(
"The value of '%s' refers to '%s', which does not refer to a Field." % (label, field),
obj=obj.__class__,
id='admin.E116',
)
]
else:
return []
0
Example 123
def _check_list_editable_item(self, obj, model, field_name, label):
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.E121')
else:
if field_name not in obj.list_display:
return [
checks.Error(
"The value of '%s' refers to '%s', which is not "
"contained in 'list_display'." % (label, field_name),
obj=obj.__class__,
id='admin.E122',
)
]
elif obj.list_display_links and field_name in obj.list_display_links:
return [
checks.Error(
"The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name,
obj=obj.__class__,
id='admin.E123',
)
]
# If list_display[0] is in list_editable, check that
# list_display_links is set. See #22792 and #26229 for use cases.
elif (obj.list_display[0] == field_name and not obj.list_display_links and
obj.list_display_links is not None):
return [
checks.Error(
"The value of '%s' refers to the first field in 'list_display' ('%s'), "
"which cannot be used unless 'list_display_links' is set." % (
label, obj.list_display[0]
),
obj=obj.__class__,
id='admin.E124',
)
]
elif not field.editable:
return [
checks.Error(
"The value of '%s' refers to '%s', which is not editable through the admin." % (
label, field_name
),
obj=obj.__class__,
id='admin.E125',
)
]
else:
return []
0
Example 124
Project: django Source File: checks.py
def check_user_model(app_configs=None, **kwargs):
if app_configs is None:
cls = apps.get_model(settings.AUTH_USER_MODEL)
else:
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
for app_config in app_configs:
if app_config.label == app_label:
cls = app_config.get_model(model_name)
break
else:
# Checks might be run against a set of app configs that don't
# include the specified user model. In this case we simply don't
# perform the checks defined below.
return []
errors = []
# Check that REQUIRED_FIELDS is a list
if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)):
errors.append(
checks.Error(
"'REQUIRED_FIELDS' must be a list or tuple.",
obj=cls,
id='auth.E001',
)
)
# Check that the USERNAME FIELD isn't included in REQUIRED_FIELDS.
if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS:
errors.append(
checks.Error(
"The field named as the 'USERNAME_FIELD' "
"for a custom user model must not be included in 'REQUIRED_FIELDS'.",
obj=cls,
id='auth.E002',
)
)
# Check that the username field is unique
if not cls._meta.get_field(cls.USERNAME_FIELD).unique:
if (settings.AUTHENTICATION_BACKENDS ==
['django.contrib.auth.backends.ModelBackend']):
errors.append(
checks.Error(
"'%s.%s' must be unique because it is named as the 'USERNAME_FIELD'." % (
cls._meta.object_name, cls.USERNAME_FIELD
),
obj=cls,
id='auth.E003',
)
)
else:
errors.append(
checks.Warning(
"'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique." % (
cls._meta.object_name, cls.USERNAME_FIELD
),
hint='Ensure that your authentication backend(s) can handle non-unique usernames.',
obj=cls,
id='auth.W004',
)
)
if isinstance(cls().is_anonymous, MethodType):
errors.append(
checks.Critical(
'%s.is_anonymous must be an attribute or property rather than '
'a method. Ignoring this is a security issue as anonymous '
'users will be treated as authenticated!' % cls,
obj=cls,
id='auth.C009',
)
)
if isinstance(cls().is_authenticated, MethodType):
errors.append(
checks.Critical(
'%s.is_authenticated must be an attribute or property rather '
'than a method. Ignoring this is a security issue as anonymous '
'users will be treated as authenticated!' % cls,
obj=cls,
id='auth.C010',
)
)
return errors
0
Example 125
Project: django Source File: checks.py
def check_models_permissions(app_configs=None, **kwargs):
if app_configs is None:
models = apps.get_models()
else:
models = chain.from_iterable(app_config.get_models() for app_config in app_configs)
Permission = apps.get_model('auth', 'Permission')
permission_name_max_length = Permission._meta.get_field('name').max_length
errors = []
for model in models:
opts = model._meta
builtin_permissions = dict(_get_builtin_permissions(opts))
# Check builtin permission name length.
max_builtin_permission_name_length = (
max(len(name) for name in builtin_permissions.values())
if builtin_permissions else 0
)
if max_builtin_permission_name_length > permission_name_max_length:
verbose_name_max_length = (
permission_name_max_length - (max_builtin_permission_name_length - len(opts.verbose_name_raw))
)
errors.append(
checks.Error(
"The verbose_name of model '%s.%s' must be at most %d characters "
"for its builtin permission names to be at most %d characters." % (
opts.app_label, opts.object_name, verbose_name_max_length, permission_name_max_length
),
obj=model,
id='auth.E007',
)
)
codenames = set()
for codename, name in opts.permissions:
# Check custom permission name length.
if len(name) > permission_name_max_length:
errors.append(
checks.Error(
"The permission named '%s' of model '%s.%s' is longer than %d characters." % (
name, opts.app_label, opts.object_name, permission_name_max_length
),
obj=model,
id='auth.E008',
)
)
# Check custom permissions codename clashing.
if codename in builtin_permissions:
errors.append(
checks.Error(
"The permission codenamed '%s' clashes with a builtin permission "
"for model '%s.%s'." % (
codename, opts.app_label, opts.object_name
),
obj=model,
id='auth.E005',
)
)
elif codename in codenames:
errors.append(
checks.Error(
"The permission codenamed '%s' is duplicated for model '%s.%s'." % (
codename, opts.app_label, opts.object_name
),
obj=model,
id='auth.E006',
)
)
codenames.add(codename)
return errors
0
Example 126
def _check_relation(self, obj, parent_model):
# There's no FK, but we do need to confirm that the ct_field and ct_fk_field are valid,
# and that they are part of a GenericForeignKey.
gfks = [
f for f in obj.model._meta.private_fields
if isinstance(f, GenericForeignKey)
]
if len(gfks) == 0:
return [
checks.Error(
"'%s.%s' has no GenericForeignKey." % (
obj.model._meta.app_label, obj.model._meta.object_name
),
obj=obj.__class__,
id='admin.E301'
)
]
else:
# Check that the ct_field and ct_fk_fields exist
try:
obj.model._meta.get_field(obj.ct_field)
except FieldDoesNotExist:
return [
checks.Error(
"'ct_field' references '%s', which is not a field on '%s.%s'." % (
obj.ct_field, obj.model._meta.app_label, obj.model._meta.object_name
),
obj=obj.__class__,
id='admin.E302'
)
]
try:
obj.model._meta.get_field(obj.ct_fk_field)
except FieldDoesNotExist:
return [
checks.Error(
"'ct_fk_field' references '%s', which is not a field on '%s.%s'." % (
obj.ct_fk_field, obj.model._meta.app_label, obj.model._meta.object_name
),
obj=obj.__class__,
id='admin.E303'
)
]
# There's one or more GenericForeignKeys; make sure that one of them
# uses the right ct_field and ct_fk_field.
for gfk in gfks:
if gfk.ct_field == obj.ct_field and gfk.fk_field == obj.ct_fk_field:
return []
return [
checks.Error(
"'%s.%s' has no GenericForeignKey using content type field '%s' and object ID field '%s'." % (
obj.model._meta.app_label, obj.model._meta.object_name, obj.ct_field, obj.ct_fk_field
),
obj=obj.__class__,
id='admin.E304'
)
]
0
Example 127
Project: django Source File: fields.py
def _check_content_type_field(self):
"""
Check if field named `field_name` in model `model` exists and is a
valid content_type field (is a ForeignKey to ContentType).
"""
try:
field = self.model._meta.get_field(self.ct_field)
except FieldDoesNotExist:
return [
checks.Error(
"The GenericForeignKey content type references the non-existent field '%s.%s'." % (
self.model._meta.object_name, self.ct_field
),
obj=self,
id='contenttypes.E002',
)
]
else:
if not isinstance(field, models.ForeignKey):
return [
checks.Error(
"'%s.%s' is not a ForeignKey." % (
self.model._meta.object_name, self.ct_field
),
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=self,
id='contenttypes.E003',
)
]
elif field.remote_field.model != ContentType:
return [
checks.Error(
"'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % (
self.model._meta.object_name, self.ct_field
),
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
),
obj=self,
id='contenttypes.E004',
)
]
else:
return []
0
Example 128
Project: django Source File: model_checks.py
def _check_lazy_references(apps, ignore=None):
"""
Ensure all lazy (i.e. string) model references have been resolved.
Lazy references are used in various places throughout Django, primarily in
related fields and model signals. Identify those common cases and provide
more helpful error messages for them.
The ignore parameter is used by StateApps to exclude swappable models from
this check.
"""
pending_models = set(apps._pending_operations) - (ignore or set())
# Short circuit if there aren't any errors.
if not pending_models:
return []
from django.db.models import signals
model_signals = {
signal: name for name, signal in vars(signals).items()
if isinstance(signal, signals.ModelSignal)
}
def extract_operation(obj):
"""
Take a callable found in Apps._pending_operations and identify the
original callable passed to Apps.lazy_model_operation(). If that
callable was a partial, return the inner, non-partial function and
any arguments and keyword arguments that were supplied with it.
obj is a callback defined locally in Apps.lazy_model_operation() and
annotated there with a `func` attribute so as to imitate a partial.
"""
operation, args, keywords = obj, [], {}
while hasattr(operation, 'func'):
# The or clauses are redundant but work around a bug (#25945) in
# functools.partial in Python 3 <= 3.5.1 and Python 2 <= 2.7.11.
args.extend(getattr(operation, 'args', []) or [])
keywords.update(getattr(operation, 'keywords', {}) or {})
operation = operation.func
return operation, args, keywords
def app_model_error(model_key):
try:
apps.get_app_config(model_key[0])
model_error = "app '%s' doesn't provide model '%s'" % model_key
except LookupError:
model_error = "app '%s' isn't installed" % model_key[0]
return model_error
# Here are several functions which return CheckMessage instances for the
# most common usages of lazy operations throughout Django. These functions
# take the model that was being waited on as an (app_label, modelname)
# pair, the original lazy function, and its positional and keyword args as
# determined by extract_operation().
def field_error(model_key, func, args, keywords):
error_msg = (
"The field %(field)s was declared with a lazy reference "
"to '%(model)s', but %(model_error)s."
)
params = {
'model': '.'.join(model_key),
'field': keywords['field'],
'model_error': app_model_error(model_key),
}
return Error(error_msg % params, obj=keywords['field'], id='fields.E307')
def signal_connect_error(model_key, func, args, keywords):
error_msg = (
"%(receiver)s was connected to the '%(signal)s' signal with a "
"lazy reference to the sender '%(model)s', but %(model_error)s."
)
receiver = args[0]
# The receiver is either a function or an instance of class
# defining a `__call__` method.
if isinstance(receiver, types.FunctionType):
description = "The function '%s'" % receiver.__name__
elif isinstance(receiver, types.MethodType):
description = "Bound method '%s.%s'" % (receiver.__self__.__class__.__name__, receiver.__name__)
else:
description = "An instance of class '%s'" % receiver.__class__.__name__
signal_name = model_signals.get(func.__self__, 'unknown')
params = {
'model': '.'.join(model_key),
'receiver': description,
'signal': signal_name,
'model_error': app_model_error(model_key),
}
return Error(error_msg % params, obj=receiver.__module__, id='signals.E001')
def default_error(model_key, func, args, keywords):
error_msg = "%(op)s contains a lazy reference to %(model)s, but %(model_error)s."
params = {
'op': func,
'model': '.'.join(model_key),
'model_error': app_model_error(model_key),
}
return Error(error_msg % params, obj=func, id='models.E022')
# Maps common uses of lazy operations to corresponding error functions
# defined above. If a key maps to None, no error will be produced.
# default_error() will be used for usages that don't appear in this dict.
known_lazy = {
('django.db.models.fields.related', 'resolve_related_class'): field_error,
('django.db.models.fields.related', 'set_managed'): None,
('django.dispatch.dispatcher', 'connect'): signal_connect_error,
}
def build_error(model_key, func, args, keywords):
key = (func.__module__, func.__name__)
error_fn = known_lazy.get(key, default_error)
return error_fn(model_key, func, args, keywords) if error_fn else None
return sorted(filter(None, (
build_error(model_key, *extract_operation(func))
for model_key in pending_models
for func in apps._pending_operations[model_key]
)), key=lambda error: error.msg)
0
Example 129
Project: django Source File: tests.py
@isolate_apps('check_framework', kwarg_name='apps')
@override_system_checks([checks.model_checks.check_all_models])
def test_model_check_method_not_shadowed(self, apps):
class ModelWithAttributeCalledCheck(models.Model):
check = 42
class ModelWithFieldCalledCheck(models.Model):
check = models.IntegerField()
class ModelWithRelatedManagerCalledCheck(models.Model):
pass
class ModelWithDescriptorCalledCheck(models.Model):
check = models.ForeignKey(ModelWithRelatedManagerCalledCheck, models.CASCADE)
article = models.ForeignKey(
ModelWithRelatedManagerCalledCheck,
models.CASCADE,
related_name='check',
)
errors = checks.run_checks(app_configs=apps.get_app_configs())
expected = [
Error(
"The 'ModelWithAttributeCalledCheck.check()' class method is "
"currently overridden by 42.",
obj=ModelWithAttributeCalledCheck,
id='models.E020'
),
Error(
"The 'ModelWithRelatedManagerCalledCheck.check()' class method is "
"currently overridden by %r." % ModelWithRelatedManagerCalledCheck.check,
obj=ModelWithRelatedManagerCalledCheck,
id='models.E020'
),
Error(
"The 'ModelWithDescriptorCalledCheck.check()' class method is "
"currently overridden by %r." % ModelWithDescriptorCalledCheck.check,
obj=ModelWithDescriptorCalledCheck,
id='models.E020'
),
]
self.assertEqual(errors, expected)
0
Example 130
Project: django-bmf Source File: apps.py
@register()
def checks(app_configs, **kwargs): # noqa
errors = []
if not apps.is_installed('django.contrib.admin'): # pragma: no cover
errors.append(Error(
'django.contrib.admin not found',
hint="Put 'django.contrib.admin' in your INSTALLED_APPS setting",
id='djangobmf.E001',
))
if not apps.is_installed('django.contrib.contenttypes'): # pragma: no cover
errors.append(Error(
'django.contrib.contenttypes not found',
hint="Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting",
id='djangobmf.E002',
))
if 'django.contrib.auth.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS: # pragma: no cover
errors.append(Error(
'django.contrib.auth.context_processors not found',
hint="Put 'django.contrib.auth.context_processors' in your TEMPLATE_CONTEXT_PROCESSORS setting",
id='djangobmf.E003',
))
return errors
0
Example 131
Project: django-pg-fts Source File: fields.py
def check(self, **kwargs):
errors = super(TSVectorField, self).check(**kwargs)
for f in self.fields:
field = None
if isinstance(f, (tuple, list)):
if len(f) > 2:
errors.append(
checks.Error(
'Invalid value in fields "%s"' % (str(f),),
hint='can be "field" or ("field", "rank")',
obj=self,
id='fts.E001'
)
)
else:
field = f[0]
if f[1].upper() not in self.RANK_LEVELS:
errors.append(
checks.Error(
'Invalid rank "%s" in "%s"' % (str(f[1]), f),
hint=('Available ranks %s' %
' or '.join(self.RANK_LEVELS)),
obj=self,
id='fts.E001'
)
)
else:
field = f
if field and not isinstance(field, six.string_types):
errors.append(
checks.Error(
'Invalid value in fields "%s"' % (str(f),),
hint='can be name of field or (field, rank)',
obj=self,
id='fts.E001'
)
)
elif field:
try:
t = self.model._meta.get_field_by_name(field)[0]
if not isinstance(t, (models.CharField, models.TextField)):
errors.append(
checks.Error(
'Field must be CharField or TextField.',
hint=None,
obj=self,
id='fts.E001'
)
)
except models.FieldDoesNotExist:
errors.append(
checks.Error(
'FieldDoesNotExistFieldDoesNotExist %s' % str(f),
hint=None,
obj=self,
id='fts.E001'
)
)
return errors
0
Example 132
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 []
0
Example 133
Project: django-debug-toolbar Source File: apps.py
@register
def check_middleware(app_configs, **kwargs):
from debug_toolbar.middleware import DebugToolbarMiddleware
errors = []
gzip_index = None
debug_toolbar_index = None
setting = getattr(settings, 'MIDDLEWARE', None)
setting_name = 'MIDDLEWARE'
if setting is None:
setting = settings.MIDDLEWARE_CLASSES
setting_name = 'MIDDLEWARE_CLASSES'
# Determine the indexes which gzip and/or the toolbar are installed at
for i, middleware in enumerate(setting):
if is_middleware_class(GZipMiddleware, middleware):
gzip_index = i
elif is_middleware_class(DebugToolbarMiddleware, middleware):
debug_toolbar_index = i
if debug_toolbar_index is None:
# If the toolbar does not appear, report an error.
errors.append(
Error(
"debug_toolbar.middleware.DebugToolbarMiddleware is missing "
"from %s." % setting_name,
hint="Add debug_toolbar.middleware.DebugToolbarMiddleware to "
"%s." % setting_name,
)
)
elif gzip_index is not None and debug_toolbar_index < gzip_index:
# If the toolbar appears before the gzip index, report an error.
errors.append(
Error(
"debug_toolbar.middleware.DebugToolbarMiddleware occurs before "
"django.middleware.gzip.GZipMiddleware in %s." % setting_name,
hint="Move debug_toolbar.middleware.DebugToolbarMiddleware to "
"after django.middleware.gzip.GZipMiddleware in %s." % setting_name,
)
)
return errors
0
Example 134
Project: django-debug-toolbar Source File: test_integration.py
@override_settings(
MIDDLEWARE=None,
MIDDLEWARE_CLASSES=[
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.gzip.GZipMiddleware',
]
)
def test_check_gzip_middleware_error(self):
messages = run_checks()
self.assertEqual(
messages,
[
Error(
"debug_toolbar.middleware.DebugToolbarMiddleware occurs "
"before django.middleware.gzip.GZipMiddleware in "
"MIDDLEWARE_CLASSES.",
hint="Move debug_toolbar.middleware.DebugToolbarMiddleware "
"to after django.middleware.gzip.GZipMiddleware in "
"MIDDLEWARE_CLASSES.",
),
]
)
0
Example 135
Project: VolUtility Source File: checks.py
@register(Tags.compatibility)
def compat_check(app_configs=None, **kwargs):
errors = []
# Imports first
try:
import pymongo
have_mongo = True
except ImportError:
have_mongo = False
errors.append(Error('Unable to import pymongo', hint='sudo pip install pymongo'))
try:
from Registry import Registry
except ImportError:
errors.append(Error('Unable to import python-registry', hint='sudo pip install python-registry'))
try:
from virus_total_apis import PublicApi
except ImportError:
errors.append(Warning('Unable to import virustotalapi', hint='sudo pip install virustotal-api'))
try:
import yara
except ImportError:
errors.append(Warning('Unable to import Yara', hint='Read the Wiki or google Yara'))
try:
import distorm3
except ImportError:
errors.append(Warning('Unable to import distorm3', hint='sudo pip install distorm3'))
# Check Vol Version
try:
vol_ver = vol_interface.vol_version.split('.')
if int(vol_ver[1]) < 5:
errors.append(Error('Unsupported Volatility version found. Need 2.5 or greater. Found: {0}'.format('.'.join(vol_ver))))
except Exception as error:
errors.append(Error('Unable to find Volatility Version Number', hint='Read the installation wiki'))
# Config
try:
from common import Config
config = Config()
if config.valid:
pass
except:
errors.append(Error('Unable to parse a volutility.conf file', hint='Copy volutiltiy.conf.sample to volutitliy.conf'))
# Database Connection finally
if have_mongo:
try:
if config.valid:
mongo_uri = config.mongo_uri
else:
mongo_uri = 'mongodb://localhost'
connection = pymongo.MongoClient(mongo_uri)
# Version Check
server_version = connection.server_info()['version']
if int(server_version[0]) < 3:
errors.append(Error(str('Incompatible MongoDB Version detected. Requires 3 or higher. Found {0}'.format(server_version))))
connection.close()
except Exception as error:
errors.append(Error('Unable to connect to MongoDB: {0}'.format(error)))
return errors
0
Example 136
@classmethod
def _check_ordering(cls):
if not cls._meta.ordering:
return []
if not isinstance(cls._meta.ordering, (list, tuple)):
return [checks.Error("'ordering' must be a tuple or list.",
hint=None, obj=cls, id='models.E014')]
fields = [f for f in cls._meta.ordering if f != '?']
fields = [f[1:] if f.startswith('-') else f for f in fields]
fields = set(f for f in fields if f not in ('_order', 'pk') and '__' not in f)
valid_fields = set(chain.from_iterable(
(f.name, f.attname)
for f in cls._meta.fields
))
valid_tfields = set(chain.from_iterable(
(f.name, f.attname)
for f in cls._meta.translations_model._meta.fields
if f.name not in ('master', 'language_code')
))
return [checks.Error("'ordering' refers to the non-existent field '%s' --hvad." % field,
hint=None, obj=cls, id='models.E015')
for field in fields - valid_fields - valid_tfields]
0
Example 137
Project: django-timezone-utils Source File: fields.py
def _check_timezone_max_length_attribute(self): # pragma: no cover
"""
Checks that the `max_length` attribute covers all possible pytz
timezone lengths.
"""
# Retrieve the maximum possible length for the time zone string
possible_max_length = max(map(len, pytz.all_timezones))
# Make sure that the max_length attribute will handle the longest time
# zone string
if self.max_length < possible_max_length: # pragma: no cover
return [
checks.Error(
msg=(
"'max_length' is too short to support all possible "
"pytz time zones."
),
hint=(
"pytz {version}'s longest time zone string has a "
"length of {value}, although it is recommended that "
"you leave room for longer time zone strings to be "
"added in the future.".format(
version=pytz.VERSION,
value=possible_max_length
)
),
obj=self,
)
]
# When no error, return an empty list
return []
0
Example 138
def check_field(self, field, **kwargs):
"""
MySQL has the following field length restriction:
No character (varchar) fields can have a length exceeding 255
characters if they have a unique index on them.
"""
# Django 1.7
errors = super(DatabaseValidation, self).check_field(field,
**kwargs)
# Ignore any related fields.
if getattr(field, 'rel', None) is None:
field_type = field.db_type(connection)
if field_type is None:
return errors
if (field_type.startswith('varchar') # Look for CharFields...
and field.unique # ... that are unique
and (field.max_length is None or
int(field.max_length) > 255)):
errors.append(
checks.Error(
('MySQL does not allow unique CharFields to have a '
'max_length > 255.'),
hint=None,
obj=field,
id='mysql.E001',
)
)
return errors
0
Example 139
Project: django-hijack Source File: test_checks.py
def test_check_url_allowed_attributes(self):
errors = checks.check_url_allowed_attributes(HijackConfig)
self.assertFalse(errors)
with SettingsOverride(hijack_settings, HIJACK_URL_ALLOWED_ATTRIBUTES=('username',)):
errors = checks.check_url_allowed_attributes(HijackConfig)
self.assertFalse(errors)
with SettingsOverride(hijack_settings, HIJACK_URL_ALLOWED_ATTRIBUTES=('username', 'email')):
errors = checks.check_url_allowed_attributes(HijackConfig)
self.assertFalse(errors)
with SettingsOverride(hijack_settings, HIJACK_URL_ALLOWED_ATTRIBUTES=('other',)):
errors = checks.check_url_allowed_attributes(HijackConfig)
expected_errors = [
Error(
'Setting HIJACK_URL_ALLOWED_ATTRIBUTES needs to be '
'subset of (user_id, email, username)',
hint=None,
obj=hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES,
id='hijack.E001',
)
]
self.assertEqual(errors, expected_errors)
0
Example 140
Project: django-hijack Source File: test_checks.py
def test_check_staff_authorization_settings(self):
errors = checks.check_staff_authorization_settings(HijackConfig)
self.assertFalse(errors)
with SettingsOverride(hijack_settings, HIJACK_AUTHORIZE_STAFF=True):
errors = checks.check_staff_authorization_settings(HijackConfig)
self.assertFalse(errors)
with SettingsOverride(hijack_settings, HIJACK_AUTHORIZE_STAFF=True, HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF=True):
errors = checks.check_staff_authorization_settings(HijackConfig)
self.assertFalse(errors)
with SettingsOverride(hijack_settings, HIJACK_AUTHORIZE_STAFF=False, HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF=True):
errors = checks.check_staff_authorization_settings(HijackConfig)
expected_errors = [
Error(
'Setting HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF may not be True if HIJACK_AUTHORIZE_STAFF is False.',
hint=None,
obj=None,
id='hijack.E004',
)
]
self.assertEqual(errors, expected_errors)
0
Example 141
Project: gro-api Source File: fields.py
def _check_consistent_to_field(self):
"""
If the attribute :attr:`to_field` was generated from the name of the
primary key of the `to` model, make sure that every model that this
field can point to has the same primary key name.
"""
# Make sure the `to_field` has been generated if it is going to be
getattr(self, 'to_field')
if self.to_field is None and self.to is not None:
return [checks.Error(
'LayoutForeignKey could not figure out what field to point to '
'on the related model', hint=None, obj=self, id='fields.E312'
)]
if 'generated_to_field' in self.__dict__ and self.generated_to_field:
for state in system_layout.allowed_values:
with system_layout.as_value(state):
if self.to is not None and (self.to._meta.pk and
self.to._meta.pk.name) != self.to_field:
model_name = self.to._meta.object_name
return [
checks.Error(
"LayoutForeignKey on model '%s' should point "
"to a different field in the target model "
"depending on the current state. This is "
"currently not supported." % model_name,
hint=None,
obj=self,
id='fields.E313',
)
]
return []