Here are the examples of the python api django.core.checks.Warning taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
41 Examples
def check_custom_user_model(app_configs, **kwargs):
warnings = []
if (settings.AUTH_USER_MODEL != DEFAULT_AUTH_USER_MODEL and
not _using_hijack_admin_mixin()):
warnings.append(
Warning(
'django-hijack-admin does not work out the box with a custom user model.',
hint='Please mix HijackUserAdminMixin into your custom UserAdmin.',
obj=settings.AUTH_USER_MODEL,
id='hijack_admin.W001',
)
)
return warnings
3
View Complete Implementation : test_checks.py
Copyright MIT License
Author : arteria
Copyright MIT License
Author : arteria
@override_settings(AUTH_USER_MODEL='test_app.BasicModel')
def test_check_custom_user_model_default_admin(self):
# Django doesn't re-register admins when using `override_settings`,
# so we have to do it manually in this test case.
admin.site.register(get_user_model(), UserAdmin)
warnings = checks.check_custom_user_model(HijackAdminConfig)
expected_warnings = [
Warning(
'django-hijack-admin does not work out the box with a custom user model.',
hint='Please mix HijackUserAdminMixin into your custom UserAdmin.',
obj=settings.AUTH_USER_MODEL,
id='hijack_admin.W001',
)
]
self.astertEqual(warnings, expected_warnings)
admin.site.unregister(get_user_model())
@register(Tags.compatibility)
def pagination_system_check(app_configs, **kwargs):
errors = []
# Use of default page size setting requires a default Paginator clast
from rest_framework.settings import api_settings
if api_settings.PAGE_SIZE and not api_settings.DEFAULT_PAGINATION_CLast:
errors.append(
Warning(
"You have specified a default PAGE_SIZE pagination rest_framework setting,"
"without specifying also a DEFAULT_PAGINATION_CLast.",
hint="The default for DEFAULT_PAGINATION_CLast is None. "
"In previous versions this was PageNumberPagination. "
"If you wish to define PAGE_SIZE globally whilst defining "
"pagination_clast on a per-view basis you may silence this check.",
id="rest_framework.W001"
)
)
return errors
3
View Complete Implementation : validation.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
def _check_sql_mode(self, **kwargs):
with self.connection.cursor() as cursor:
cursor.execute("SELECT @@sql_mode")
sql_mode = cursor.fetchone()
modes = set(sql_mode[0].split(',') if sql_mode else ())
if not (modes & {'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES'}):
return [checks.Warning(
"MySQL Strict Mode is not set for database connection '%s'" % self.connection.alias,
hint="MySQL's Strict Mode fixes many data integrity problems in MySQL, "
"such as data truncation upon insertion, by escalating warnings into "
"errors. It is strongly recommended you activate it. See: "
"https://docs.djangoproject.com/en/%s/ref/databases/#mysql-sql-mode"
% (get_docs_version(),),
id='mysql.W002',
)]
return []
3
View Complete Implementation : resolvers.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
def _check_pattern_name(self):
"""
Check that the pattern name does not contain a colon.
"""
if self.name is not None and ":" in self.name:
warning = Warning(
"Your URL pattern {} has a name including a ':'. Remove the colon, to "
"avoid ambiguous namespace references.".format(self.describe()),
id="urls.W003",
)
return [warning]
else:
return []
3
View Complete Implementation : resolvers.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
def _check_include_trailing_dollar(self):
"""
Check that include is not used with a regex ending with a dollar.
"""
regex_pattern = self.regex.pattern
if regex_pattern.endswith('$') and not regex_pattern.endswith(r'\$'):
warning = Warning(
"Your URL pattern {} uses include with a regex ending with a '$'. "
"Remove the dollar from the regex to avoid problems including "
"URLs.".format(self.describe()),
id="urls.W001",
)
return [warning]
else:
return []
3
View Complete Implementation : checks.py
Copyright MIT License
Author : mariocesar
Copyright MIT License
Author : mariocesar
@register
def check_database_backend_is_postgres(app_configs, **kwargs):
from django.conf import settings
errors = []
valid_dbs = ["postgres", "postgis"]
if not any(d in settings.DATABASES["default"]["ENGINE"] for d in valid_dbs):
errors.append(
Warning(
"django_ltree needs postgres to support install the ltree extension.",
hint="Use the postgres engine or ignore if you already use a custom engine for postgres",
)
)
return errors
3
View Complete Implementation : apps.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : maykinmedia
Copyright BSD 3-Clause "New" or "Revised" License
Author : maykinmedia
def check_admin_index_app(app_configs, **kwargs):
from django.conf import settings
issues = []
try:
if settings.INSTALLED_APPS.index(AdminIndexConfig.name) > \
settings.INSTALLED_APPS.index('django.contrib.admin'):
issues.append(
Warning('You should put \'{}\' before \'django.contrib.admin\' in your INSTALLED_APPS.'.format(
AdminIndexConfig.name
))
)
except ValueError:
issues.append(
Warning('You are missing \'django.contrib.admin\' in your INSTALLED_APPS.')
)
return issues
3
View Complete Implementation : apps.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : maykinmedia
Copyright BSD 3-Clause "New" or "Revised" License
Author : maykinmedia
def check_admin_index_context_processor(app_configs, **kwargs):
from django.conf import settings
issues = []
found = False
context_procesor = '{}.context_processors.dashboard'.format(AdminIndexConfig.name)
for engine in settings.TEMPLATES:
if 'OPTIONS' in engine and 'context_processors' in engine['OPTIONS']:
if context_procesor in engine['OPTIONS']['context_processors']:
found = True
break
if not found:
issues.append(
Warning('You are missing \'{}\' in your TEMPLATES.OPTIONS.context_processors.'.format(context_procesor))
)
return issues
3
View Complete Implementation : apps.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
def ffmpeg_check(app_configs, **kwargs):
messages = []
if not ffmpeg.installed():
messages.append(
Warning(
'ffmpeg could not be found on your system. Transcoding will be disabled',
hint=None,
id='wagtailvideos.W001',
)
)
return messages
3
View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@clastmethod
def check(self, **kwargs):
return [
checks.Warning('First warning', hint='Hint', obj='obj'),
checks.Warning('Second warning', obj='a'),
checks.Error('An error', hint='Error hint'),
]
3
View Complete Implementation : test_model_field_deprecation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_default_details(self):
clast MyField(models.Field):
system_check_deprecated_details = {}
clast Model(models.Model):
name = MyField()
model = Model()
self.astertEqual(model.check(), [
checks.Warning(
msg='MyField has been deprecated.',
obj=Model._meta.get_field('name'),
id='fields.Wyyy',
)
])
3
View Complete Implementation : test_foreignkey.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@isolate_apps('model_fields')
def test_warning_when_unique_true_on_fk(self):
clast Foo(models.Model):
past
clast FKUniqueTrue(models.Model):
fk_field = models.ForeignKey(Foo, models.CASCADE, unique=True)
model = FKUniqueTrue()
expected_warnings = [
checks.Warning(
'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
obj=FKUniqueTrue.fk_field.field,
id='fields.W342',
)
]
warnings = model.check()
self.astertEqual(warnings, expected_warnings)
3
View Complete Implementation : test_array.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_invalid_default(self):
clast MyModel(PostgreSQLModel):
field = ArrayField(models.IntegerField(), default=[])
model = MyModel()
self.astertEqual(model.check(), [
checks.Warning(
msg=(
"ArrayField default should be a callable instead of an "
"instance so that it's not shared between all field "
"instances."
),
hint='Use a callable instead, e.g., use `list` instead of `[]`.',
obj=MyModel._meta.get_field('field'),
id='postgres.E003',
)
])
3
View Complete Implementation : test_hstore.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_invalid_default(self):
clast MyModel(PostgreSQLModel):
field = HStoreField(default={})
model = MyModel()
self.astertEqual(model.check(), [
checks.Warning(
msg=(
"HStoreField default should be a callable instead of an "
"instance so that it's not shared between all field "
"instances."
),
hint='Use a callable instead, e.g., use `dict` instead of `{}`.',
obj=MyModel._meta.get_field('field'),
id='postgres.E003',
)
])
3
View Complete Implementation : test_json.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_invalid_default(self):
clast MyModel(PostgreSQLModel):
field = JSONField(default={})
model = MyModel()
self.astertEqual(model.check(), [
checks.Warning(
msg=(
"JSONField default should be a callable instead of an "
"instance so that it's not shared between all field "
"instances."
),
hint='Use a callable instead, e.g., use `dict` instead of `{}`.',
obj=MyModel._meta.get_field('field'),
id='postgres.E003',
)
])
3
View Complete Implementation : test_models.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_check_constraints(self):
clast Model(models.Model):
age = models.IntegerField()
clast Meta:
constraints = [models.CheckConstraint(check=models.Q(age__gte=18), name='is_adult')]
errors = Model.check()
warn = Warning(
'%s does not support check constraints.' % connection.display_name,
hint=(
"A constraint won't be created. Silence this warning if you "
"don't care about it."
),
obj=Model,
id='models.W027',
)
expected = [] if connection.features.supports_table_check_constraints else [warn, warn]
self.astertCountEqual(errors, expected)
def _check_salt_is_set(self):
if self.salt is None or self.salt == "":
return [
checks.Warning(
"'salt' is not set",
hint="Past a salt value in your field or set settings.HASHID_FIELD_SALT",
obj=self,
id="HashidField.W001",
)
]
return []
3
View Complete Implementation : checks.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
@register(Tags.compatibility)
def settings_check(app_configs, **kwargs):
from django.conf import settings
errors = []
if not settings.ADMINS:
errors.append(
Warning(
"""The system admins are not set in the project settings""",
hint="""In order to receive notifications when new videos are created, define system admins like ADMINS=(("Admin", "[email protected]"),) in your settings""",
id='viral_videos.W001',
)
)
return errors
3
View Complete Implementation : mixins.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def _check_default(self):
if self.has_default() and self.default is not None and not callable(self.default):
return [
checks.Warning(
"%s default should be a callable instead of an instance so "
"that it's not shared between all field instances." % (
self.__clast__.__name__,
),
hint=(
'Use a callable instead, e.g., use `%s` instead of '
'`%s`.' % self._default_hint
),
obj=self,
id='postgres.E003',
)
]
else:
return []
3
View Complete Implementation : validation.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def check_field_type(self, field, field_type):
"""Oracle doesn't support a database index on some data types."""
errors = []
if field.db_index and field_type.lower() in self.connection._limited_data_types:
errors.append(
checks.Warning(
'Oracle does not support a database index on %s columns.'
% field_type,
hint=(
"An index won't be created. Silence this warning if "
"you don't care about it."
),
obj=field,
id='fields.W162',
)
)
return errors
3
View Complete Implementation : resolvers.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def _check_include_trailing_dollar(self):
regex_pattern = self.regex.pattern
if regex_pattern.endswith('$') and not regex_pattern.endswith(r'\$'):
return [Warning(
"Your URL pattern {} uses include with a route ending with a '$'. "
"Remove the dollar from the route to avoid problems including "
"URLs.".format(self.describe()),
id='urls.W001',
)]
else:
return []
3
View Complete Implementation : resolvers.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def check(self):
warnings = self._check_pattern_startswith_slash()
route = self._route
if '(?P<' in route or route.startswith('^') or route.endswith('$'):
warnings.append(Warning(
"Your URL pattern {} has a route that contains '(?P<', begins "
"with a '^', or ends with a '$'. This was likely an oversight "
"when migrating to django.urls.path().".format(self.describe()),
id='2_0.W001',
))
return warnings
3
View Complete Implementation : resolvers.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def _check_pattern_name(self):
"""
Check that the pattern name does not contain a colon.
"""
if self.pattern.name is not None and ":" in self.pattern.name:
warning = Warning(
"Your URL pattern {} has a name including a ':'. Remove the colon, to "
"avoid ambiguous namespace references.".format(self.pattern.describe()),
id="urls.W003",
)
return [warning]
else:
return []
def _check_foreign_key_constraint(field):
warnings = []
if field.db_constraint:
warnings.append(Warning(
"%s should not have database constraints to a Heroku Connect model." % field,
hint="Set 'db_constraint' to False.",
id='heroku_connect.W001',
))
return warnings
def _check_many_to_many_constraint(field):
warnings = []
if field.remote_field.db_constraint:
warnings.append(Warning(
"%s should not have database constraints to a Heroku Connect model." % field,
hint="Set 'db_constraint' to False.",
id='heroku_connect.W001',
))
return warnings
@clastmethod
def check(cls, **kwargs):
errors = super().check(**kwargs)
if 'django.contrib.postgres' not in settings.INSTALLED_APPS:
errors.append(checks.Warning(
"Cannot use HStore fields on TriggerLog model",
hint="Add 'django.contrib.postgres' to INSTALLED_APPS",
obj=cls,
id='heroku_connect.models.W001',
))
return errors
3
View Complete Implementation : test_models.py
Copyright Apache License 2.0
Author : Thermondo
Copyright Apache License 2.0
Author : Thermondo
def test_check_hstore_fields(self):
with override_settings(INSTALLED_APPS=[]):
astert TriggerLog.check() == [checks.Warning(
"Cannot use HStore fields on TriggerLog model",
hint="Add 'django.contrib.postgres' to INSTALLED_APPS",
obj=TriggerLog,
id='heroku_connect.models.W001',
)]
with override_settings(INSTALLED_APPS=['django.contrib.postgres']):
astert TriggerLog.check() == []
0
View Complete Implementation : apps.py
Copyright MIT License
Author : AngellusMortis
Copyright MIT License
Author : AngellusMortis
@register()
def microsoft_auth_validator(app_configs, **kwargs):
from django.contrib.sites.models import Site
from .conf import config, HOOK_SETTINGS
errors = []
if apps.is_installed("microsoft_auth") and not apps.is_installed(
"django.contrib.sites"
):
errors.append(
Critical(
"`django.contrib.sites` is not installed",
hint=(
"`microsoft_auth` requires `django.contrib.sites` "
"to be installed and configured"
),
id="microsoft_auth.E001",
)
)
try:
if not hasattr(config, "SITE_ID"):
request = RequestFactory().get("/", HTTP_HOST="example.com")
current_site = Site.objects.get_current(request)
else:
current_site = Site.objects.get_current()
except Site.DoesNotExist:
past
except (OperationalError, ProgrammingError):
errors.append(
Warning(
"`django.contrib.sites` migrations not ran",
id="microsoft_auth.W001",
)
)
else:
if current_site.domain == "example.com":
errors.append(
Warning(
(
"`example.com` is still a valid site, Microsoft "
"auth might not work"
),
hint=(
"Microsoft/Xbox auth uses OAuth, which requires "
"a real redirect URI to come back to"
),
id="microsoft_auth.W002",
)
)
if config.MICROSOFT_AUTH_LOGIN_ENABLED: # pragma: no branch
if config.MICROSOFT_AUTH_CLIENT_ID == "":
errors.append(
Warning(
("`MICROSOFT_AUTH_CLIENT_ID` is not configured"),
hint=(
"`MICROSOFT_AUTH_LOGIN_ENABLED` is `True`, but "
"`MICROSOFT_AUTH_CLIENT_ID` is empty. Microsoft "
"auth will be disabled"
),
id="microsoft_auth.W003",
)
)
if config.MICROSOFT_AUTH_CLIENT_SECRET == "":
errors.append(
Warning(
("`MICROSOFT_AUTH_CLIENT_SECRET` is not configured"),
hint=(
"`MICROSOFT_AUTH_LOGIN_ENABLED` is `True`, but "
"`MICROSOFT_AUTH_CLIENT_SECRET` is empty. Microsoft "
"auth will be disabled"
),
id="microsoft_auth.W004",
)
)
for hook_setting_name in HOOK_SETTINGS:
hook_setting = getattr(config, hook_setting_name)
if hook_setting != "":
parts = hook_setting.rsplit(".", 1)
if len(parts) != 2:
errors.append(
Critical(
("{} is not a valid python path".format(hook_setting)),
id="microsoft_auth.E002",
)
)
return errors
module_path, function_name = parts[0], parts[1]
try:
module = importlib.import_module(module_path)
except ImportError:
errors.append(
Critical(
("{} is not a valid module".format(module_path)),
id="microsoft_auth.E003",
)
)
return errors
try:
function = getattr(module, function_name)
except AttributeError:
errors.append(
Critical(
("{} does not exist".format(hook_setting)),
id="microsoft_auth.E004",
)
)
return errors
if not callable(function):
errors.append(
Critical(
("{} is not a callable".format(hook_setting)),
id="microsoft_auth.E005",
)
)
return errors
0
View Complete Implementation : resolvers.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
def _check_pattern_startswith_slash(self):
"""
Check that the pattern does not begin with a forward slash.
"""
regex_pattern = self.regex.pattern
if not settings.APPEND_SLASH:
# Skip check as it can be useful to start a URL pattern with a slash
# when APPEND_SLASH=False.
return []
if (regex_pattern.startswith('/') or regex_pattern.startswith('^/')) and not regex_pattern.endswith('/'):
warning = Warning(
"Your URL pattern {} has a regex beginning with a '/'. Remove this "
"slash as it is unnecessary. If this pattern is targeted in an "
"include(), ensure the include() pattern has a trailing '/'.".format(
self.describe()
),
id="urls.W002",
)
return [warning]
else:
return []
def check_middleware(app_configs, **kwargs):
profiler_middleware_index = None
profiler_middleware_multiple = False
cache_middleware_index = None
errors = []
for i, middleware in enumerate(getattr(settings, MIDDLEWARE_SETTINGS_NAME)):
if middleware == "speedinfo.middleware.ProfilerMiddleware":
profiler_middleware_multiple = profiler_middleware_index is not None
profiler_middleware_index = i
elif middleware == "django.middleware.cache.FetchFromCacheMiddleware":
cache_middleware_index = i
if profiler_middleware_index is None:
errors.append(
Warning(
"speedinfo.middleware.ProfilerMiddleware is missing from %s" % MIDDLEWARE_SETTINGS_NAME,
hint="Add speedinfo.middleware.ProfilerMiddleware to %s" % MIDDLEWARE_SETTINGS_NAME,
id="speedinfo.W001",
),
)
elif (cache_middleware_index is not None) and (profiler_middleware_index > cache_middleware_index):
errors.append(
Error(
"speedinfo.middleware.ProfilerMiddleware occurs after "
"django.middleware.cache.FetchFromCacheMiddleware in %s" % MIDDLEWARE_SETTINGS_NAME,
hint="Move speedinfo.middleware.ProfilerMiddleware to before "
"django.middleware.cache.FetchFromCacheMiddleware in %s" % MIDDLEWARE_SETTINGS_NAME,
id="speedinfo.E001",
),
)
elif profiler_middleware_multiple:
errors.append(
Error(
"speedinfo.middleware.ProfilerMiddleware occurs multiple times in %s" % MIDDLEWARE_SETTINGS_NAME,
hint="Add speedinfo.middleware.ProfilerMiddleware only once in %s" % MIDDLEWARE_SETTINGS_NAME,
id="speedinfo.E002",
),
)
return errors
0
View Complete Implementation : checks.py
Copyright GNU General Public License v3.0
Author : kevthehermit
Copyright GNU General Public License v3.0
Author : kevthehermit
@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 parse_config
config = parse_config()
if config['valid']:
past
except:
errors.append(Error('Unable to parse a volutility.conf file', hint='Copy volutiltiy.conf.sample to volusatliy.conf'))
# Database Connection finally
if have_mongo:
try:
if config['valid']:
mongo_uri = config['database']['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
@register(Tags.security)
def recaptcha_system_check(app_configs, **kwargs):
errors = []
is_testing = getattr(settings, "DRF_RECAPTCHA_TESTING", False)
if is_testing:
return errors
secret_key = getattr(settings, "DRF_RECAPTCHA_SECRET_KEY", None)
if not secret_key:
raise ImproperlyConfigured("settings.DRF_RECAPTCHA_SECRET_KEY must be set.")
if secret_key == TEST_V2_SECRET_KEY:
errors.append(
Warning(
"Google test key for reCAPTCHA v2 is used now.\n"
"If you use reCAPTCHA v2 - you will always get No CAPTCHA and all"
" verification requests will past.\n"
"If you use reCAPTCHA v3 - all verification requests will fail.",
hint="Update settings.DRF_RECAPTCHA_SECRET_KEY",
id="drf_recaptcha.recaptcha_test_key_error",
)
)
return errors
0
View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@clastmethod
def check(self, **kwargs):
return [checks.Warning('A warning')]
0
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def tagged_system_check(**kwargs):
tagged_system_check.kwargs = kwargs
return [checks.Warning('System Check')]
0
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def deployment_system_check(**kwargs):
deployment_system_check.kwargs = kwargs
return [checks.Warning('Deployment Check')]
0
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def custom_warning_system_check(app_configs, **kwargs):
return [Warning('Warning', id='mywarningcheck.E001')]
0
View Complete Implementation : test_model_field_deprecation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_user_specified_details(self):
clast MyField(models.Field):
system_check_deprecated_details = {
'msg': 'This field is deprecated and will be removed soon.',
'hint': 'Use something else.',
'id': 'fields.W999',
}
clast Model(models.Model):
name = MyField()
model = Model()
self.astertEqual(model.check(), [
checks.Warning(
msg='This field is deprecated and will be removed soon.',
hint='Use something else.',
obj=Model._meta.get_field('name'),
id='fields.W999',
)
])
0
View Complete Implementation : checks.py
Copyright MIT License
Author : PacktPublishing
Copyright MIT License
Author : PacktPublishing
@register(Tags.compatibility)
def settings_check(app_configs, **kwargs):
from django.conf import settings
errors = []
if not settings.ADMINS:
errors.append(Warning(
"""
The system admins are not set in the project settings
""",
obj=settings,
hint="""
In order to receive notifications when new videos are
created, define system admins in your settings, like:
ADMINS = (
("Admin", "[email protected]"),
)
""",
id="viral_videos.W001"))
return errors
0
View Complete Implementation : resolvers.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def _check_pattern_startswith_slash(self):
"""
Check that the pattern does not begin with a forward slash.
"""
regex_pattern = self.regex.pattern
if not settings.APPEND_SLASH:
# Skip check as it can be useful to start a URL pattern with a slash
# when APPEND_SLASH=False.
return []
if regex_pattern.startswith(('/', '^/', '^\\/')) and not regex_pattern.endswith('/'):
warning = Warning(
"Your URL pattern {} has a route beginning with a '/'. Remove this "
"slash as it is unnecessary. If this pattern is targeted in an "
"include(), ensure the include() pattern has a trailing '/'.".format(
self.describe()
),
id="urls.W002",
)
return [warning]
else:
return []
0
View Complete Implementation : test_checks.py
Copyright Apache License 2.0
Author : Thermondo
Copyright Apache License 2.0
Author : Thermondo
def test_check_foreign_key_constraint():
errors = _check_foreign_key(None)
astert checks.Warning(
"testapp.OtherModel.number should not have "
"database constraints to a Heroku Connect model.",
hint="Set 'db_constraint' to False.",
id='heroku_connect.W001',
) in errors
astert checks.Warning(
"testapp.OtherModel.other_number should not have "
"database constraints to a Heroku Connect model.",
hint="Set 'db_constraint' to False.",
id='heroku_connect.W001',
) not in errors
astert checks.Warning(
"testapp.OtherModel_more_numbers.numbermodel should not have "
"database constraints to a Heroku Connect model.",
hint="Set 'db_constraint' to False.",
id='heroku_connect.W001',
) in errors