Python django.core.checks.Warning() Examples

The following are 30 code examples of django.core.checks.Warning(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.checks , or try the search function .
Example #1
Source File: resolvers.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 [] 
Example #2
Source File: validation.py    From python with Apache License 2.0 6 votes vote down vote up
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 [] 
Example #3
Source File: test_simple_modeladmin.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_model_with_single_tabbed_panel_only(self):

        Publisher.content_panels = [FieldPanel('name'), FieldPanel('headquartered_in')]

        warning = checks.Warning(
            "Publisher.content_panels will have no effect on modeladmin editing",
            hint="""Ensure that Publisher uses `panels` instead of `content_panels`\
or set up an `edit_handler` if you want a tabbed editing interface.
There are no default tabs on non-Page models so there will be no\
 Content tab for the content_panels to render in.""",
            obj=Publisher,
            id='wagtailadmin.W002',
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning, checks_results)

        # clean up for future checks
        delattr(Publisher, 'content_panels') 
Example #4
Source File: resolvers.py    From python with Apache License 2.0 6 votes vote down vote up
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 [] 
Example #5
Source File: tests.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_model_with_single_tabbed_panel_only(self):

        StandardSnippet.content_panels = [FieldPanel('text')]

        warning = checks.Warning(
            "StandardSnippet.content_panels will have no effect on snippets editing",
            hint="""Ensure that StandardSnippet uses `panels` instead of `content_panels`\
or set up an `edit_handler` if you want a tabbed editing interface.
There are no default tabs on non-Page models so there will be no\
 Content tab for the content_panels to render in.""",
            obj=StandardSnippet,
            id='wagtailadmin.W002',
        )

        checks_results = self.get_checks_result()

        self.assertEqual([warning], checks_results)

        # clean up for future checks
        delattr(StandardSnippet, 'content_panels') 
Example #6
Source File: checks.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
def check_users(app_configs=None, **kwargs):
    from django.contrib.auth import get_user_model

    errors = []

    User = get_user_model()
    try:
        admin_user = User.objects.get(username="admin")
    except (User.DoesNotExist, OperationalError, ProgrammingError):
        pass
    else:
        if admin_user.check_password("admin"):
            errors.append(
                checks.Warning(
                    _("The default 'admin' user still has a password set to 'admin'."),
                    hint=_("Remove the 'admin' user or change its password."),
                    id="pootle.W016",
                )
            )

    return errors 
Example #7
Source File: checks.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
def check_email_server_is_alive(app_configs=None, **kwargs):
    from django.conf import settings

    errors = []
    if settings.ZING_SIGNUP_ENABLED or settings.ZING_CONTACT_EMAIL.strip():
        from django.core.mail import get_connection

        connection = get_connection()
        try:
            connection.open()
        except Exception:
            errors.append(
                checks.Warning(
                    _("Email server is not available."),
                    hint=_(
                        "Review your email settings and make sure your email "
                        "server is working."
                    ),
                    id="pootle.W004",
                )
            )
        else:
            connection.close()
    return errors 
Example #8
Source File: related.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def _check_ignored_options(self, **kwargs):
        warnings = []

        if self.has_null_arg:
            warnings.append(
                checks.Warning(
                    'null has no effect on ManyToManyField.',
                    hint=None,
                    obj=self,
                    id='fields.W340',
                )
            )

        if len(self._validators) > 0:
            warnings.append(
                checks.Warning(
                    'ManyToManyField does not support validators.',
                    hint=None,
                    obj=self,
                    id='fields.W341',
                )
            )

        return warnings 
Example #9
Source File: validation.py    From bioforum with MIT License 6 votes vote down vote up
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 [] 
Example #10
Source File: validation.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #11
Source File: validation.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 
Example #12
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_page_with_inline_model_with_tabbed_panel_only(self):
        """Test that checks will warn against setting single tabbed panel on InlinePanel model"""

        EventPageSpeaker.settings_panels = [FieldPanel('first_name'), FieldPanel('last_name')]

        warning = checks.Warning(
            "EventPageSpeaker.settings_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `settings_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning, checks_results)

        delattr(EventPageSpeaker, 'settings_panels') 
Example #13
Source File: checks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def css_install_check(app_configs, **kwargs):
    errors = []

    css_path = os.path.join(
        os.path.dirname(__file__), 'static', 'wagtailadmin', 'css', 'normalize.css'
    )

    if not os.path.isfile(css_path):
        error_hint = """
            Most likely you are running a development (non-packaged) copy of
            Wagtail and have not built the static assets -
            see https://docs.wagtail.io/en/latest/contributing/developing.html

            File not found: %s
        """ % css_path

        errors.append(
            Warning(
                "CSS for the Wagtail admin is missing",
                hint=error_hint,
                id='wagtailadmin.W001',
            )
        )
    return errors 
Example #14
Source File: validation.py    From python2017 with MIT License 6 votes vote down vote up
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 [] 
Example #15
Source File: mixins.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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.__class__.__name__,
                    ),
                    hint=(
                        'Use a callable instead, e.g., use `%s` instead of '
                        '`%s`.' % self._default_hint
                    ),
                    obj=self,
                    id='postgres.E003',
                )
            ]
        else:
            return [] 
Example #16
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_ignored_options(self, **kwargs):
        warnings = []

        if self.null:
            warnings.append(
                checks.Warning(
                    'null has no effect on ManyToManyField.',
                    hint=None,
                    obj=self,
                    id='fields.W340',
                )
            )

        if len(self._validators) > 0:
            warnings.append(
                checks.Warning(
                    'ManyToManyField does not support validators.',
                    hint=None,
                    obj=self,
                    id='fields.W341',
                )
            )

        return warnings 
Example #17
Source File: validation.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 [] 
Example #18
Source File: checks.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def setting_oidc_remote_auth_header(app_configs, **kwargs):
    errors = []

    if not settings.OIDC_REMOTE_AUTH_HEADER.startswith("HTTP_"):
        msg = "The setting OIDC_REMOTE_AUTH_HEADER should start with HTTP_"
        errors.append(Warning(msg, id=WARNING_MISCONFIGURED_OIDC_REMOTE_AUTH_HEADER_PREFIX))

    return errors 
Example #19
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def _check_max_length_warning(self):
        if self.max_length is not None:
            return [
                checks.Warning(
                    "'max_length' is ignored when used with IntegerField",
                    hint="Remove 'max_length' from field",
                    obj=self,
                    id='fields.W122',
                )
            ]
        return [] 
Example #20
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def _check_deprecation_details(self):
        if self.system_check_removed_details is not None:
            return [
                checks.Error(
                    self.system_check_removed_details.get(
                        'msg',
                        '%s has been removed except for support in historical '
                        'migrations.' % self.__class__.__name__
                    ),
                    hint=self.system_check_removed_details.get('hint'),
                    obj=self,
                    id=self.system_check_removed_details.get('id', 'fields.EXXX'),
                )
            ]
        elif self.system_check_deprecated_details is not None:
            return [
                checks.Warning(
                    self.system_check_deprecated_details.get(
                        'msg',
                        '%s has been deprecated.' % self.__class__.__name__
                    ),
                    hint=self.system_check_deprecated_details.get('hint'),
                    obj=self,
                    id=self.system_check_deprecated_details.get('id', 'fields.WXXX'),
                )
            ]
        return [] 
Example #21
Source File: checks.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def utf8mb4_warning(alias):
    return Warning(
        "The character set is not utf8mb4 for database connection '{}'".format(alias),
        hint=(
            "The default 'utf8' character set does not include support for "
            + "all Unicode characters. It's strongly recommended you move to "
            + "use 'utf8mb4'. See: "
            + "https://django-mysql.readthedocs.io/en/latest/checks.html#django-mysql-w003-utf8mb4"  # noqa: B950
        ),
        id="django_mysql.W003",
    ) 
Example #22
Source File: checks.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def innodb_strict_mode_warning(alias):
    return Warning(
        "InnoDB Strict Mode is not set for database connection '{}'".format(alias),
        hint=(
            "InnoDB Strict Mode escalates several warnings around "
            + "InnoDB-specific statements into errors. It's recommended you "
            + "activate this, but it's not very likely to affect you if you "
            + "don't. See: "
            + "https://django-mysql.readthedocs.io/en/latest/checks.html#django-mysql-w002-innodb-strict-mode"  # noqa: B950
        ),
        id="django_mysql.W002",
    ) 
Example #23
Source File: checks.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def strict_mode_warning(alias):
    return Warning(
        "MySQL Strict Mode is not set for database connection '{}'".format(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://django-mysql.readthedocs.io/en/latest/checks.html#django-mysql-w001-strict-mode"  # noqa: B950
        ),
        id="django_mysql.W001",
    ) 
Example #24
Source File: geometry.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def check_speedups(app_configs, **kwargs):
    errors = []
    if not speedups.available:
        errors.append(
            checks.Warning(
                'Your shapely version does not have speedups enabled. This will significantly slow down c3nav!',
                obj='shapely.speedups',
                id='c3nav.mapdata.W001',
            )
        )
    return errors 
Example #25
Source File: related.py    From python2017 with MIT License 5 votes vote down vote up
def _check_unique(self, **kwargs):
        return [
            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=self,
                id='fields.W342',
            )
        ] if self.unique else [] 
Example #26
Source File: __init__.py    From python with Apache License 2.0 5 votes vote down vote up
def _check_max_length_warning(self):
        if self.max_length is not None:
            return [
                checks.Warning(
                    "'max_length' is ignored when used with IntegerField",
                    hint="Remove 'max_length' from field",
                    obj=self,
                    id='fields.W122',
                )
            ]
        return [] 
Example #27
Source File: test_simple_modeladmin.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_model_with_two_tabbed_panels_only(self):

        Publisher.settings_panels = [FieldPanel('name')]
        Publisher.promote_panels = [FieldPanel('headquartered_in')]


        warning_1 = checks.Warning(
            "Publisher.promote_panels will have no effect on modeladmin editing",
            hint="""Ensure that Publisher uses `panels` instead of `promote_panels`\
or set up an `edit_handler` if you want a tabbed editing interface.
There are no default tabs on non-Page models so there will be no\
 Promote tab for the promote_panels to render in.""",
            obj=Publisher,
            id='wagtailadmin.W002',
        )

        warning_2 = checks.Warning(
            "Publisher.settings_panels will have no effect on modeladmin editing",
            hint="""Ensure that Publisher uses `panels` instead of `settings_panels`\
or set up an `edit_handler` if you want a tabbed editing interface.
There are no default tabs on non-Page models so there will be no\
 Settings tab for the settings_panels to render in.""",
            obj=Publisher,
            id='wagtailadmin.W002',
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning_1, checks_results)
        self.assertIn(warning_2, checks_results)

        # clean up for future checks
        delattr(Publisher, 'settings_panels')
        delattr(Publisher, 'promote_panels') 
Example #28
Source File: resolvers.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 [] 
Example #29
Source File: test_edit_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_page_with_inline_model_with_two_tabbed_panels(self):
        """Test that checks will warn against multiple tabbed panels on InlinePanel models"""

        EventPageSpeaker.content_panels = [FieldPanel('first_name')]
        EventPageSpeaker.promote_panels = [FieldPanel('last_name')]

        warning_1 = checks.Warning(
            "EventPageSpeaker.content_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `content_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )
        warning_2 = checks.Warning(
            "EventPageSpeaker.promote_panels will have no effect on InlinePanel model editing",
            hint="""Ensure that EventPageSpeaker uses `panels` instead of `promote_panels`.
There are no tabs on non-Page model editing within InlinePanels.""",
            obj=EventPageSpeaker,
            id=self.warning_id,
        )

        checks_results = self.get_checks_result()

        self.assertIn(warning_1, checks_results)
        self.assertIn(warning_2, checks_results)

        delattr(EventPageSpeaker, 'content_panels')
        delattr(EventPageSpeaker, 'promote_panels') 
Example #30
Source File: index.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_search_fields(cls, **kwargs):
        errors = []
        for field in cls.get_search_fields():
            message = "{model}.search_fields contains non-existent field '{name}'"
            if not cls._has_field(field.field_name):
                errors.append(
                    checks.Warning(
                        message.format(model=cls.__name__, name=field.field_name),
                        obj=cls,
                    )
                )
        return errors