如何抑制Django中的否决警告?

2024-06-12 01:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

每次我使用django-admin命令——甚至在TAB-completion上——它都会抛出一个RemovedInDjango19Warning(如果我使用test命令,则会抛出更多)。我怎样才能抑制这些警告?

我正在使用Django 1.8和Python 3.4(在虚拟环境中)。据我所知,所有这些警告都来自库,而不是我的代码。

实例

下面是一些例子:

  • …/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes. return f(*args, **kwds)

  • …/lib/python3.4/site-packages/django/contrib/admin/util.py:7: RemovedInDjango19Warning: The django.contrib.admin.util module has been renamed. Use django.contrib.admin.utils instead. "Use django.contrib.admin.utils instead.", RemovedInDjango19Warning)

  • …/lib/python3.4/site-packages/django/templatetags/future.py:25: RemovedInDjango19Warning: Loading the ``url`` tag from the ``future`` library is deprecated and will be removed in Django 1.9. Use the default ``url`` tag instead. RemovedInDjango19Warning)

更新

由于Django版本1.11(release notes)默认情况下,不推荐警告不再响亮。所以我想这不再是个问题了,因为1.11是支持Python2的最后一个版本,而且还具有长期支持的特性。


Tags: andthedjangopy命令警告adminis
3条回答

我把这个留给新人:

至于django 1.11默认情况下,不推荐的警告不再响亮。例如,要激活它们,请运行python -Wd manage.py runserver

source

向settings.py添加日志过滤器可以抑制这些控制台警告(至少对于Django 1.7、Python 3.4中的manage.py命令)。

过滤器可以选择性地抑制警告。下面的代码为控制台创建一个新的“suppress_deprecated”筛选器,并将其附加到默认日志筛选器。将此块添加到settings.py以配置日志记录变量:

import logging, copy
from django.utils.log import DEFAULT_LOGGING

LOGGING = copy.deepcopy(DEFAULT_LOGGING)
LOGGING['filters']['suppress_deprecated'] = {
    '()': 'mysite.settings.SuppressDeprecated'  
}
LOGGING['handlers']['console']['filters'].append('suppress_deprecated')

class SuppressDeprecated(logging.Filter):
    def filter(self, record):
        WARNINGS_TO_SUPPRESS = [
            'RemovedInDjango18Warning',
            'RemovedInDjango19Warning'
        ]
        # Return false to suppress message.
        return not any([warn in record.getMessage() for warn in WARNINGS_TO_SUPPRESS])

如果根网站模块(或筛选器位置和/或名称)不同,则需要更改“mysite.settings.SuppressDeprecated”字符串。

在django 1.7中,引入了一个新的设置SILENCED_SYSTEM_CHECKS来抑制警告

A list of identifiers of messages generated by the system check framework (i.e. ["models.W001"]) that you wish to permanently acknowledge and ignore. Silenced warnings will no longer be output to the console; silenced errors will still be printed, but will not prevent management commands from running.

Documentation could be found here

这是一张list of all the checks to suppress 示例:

如果要取消TEMPLATES_警告

The standalone TEMPLATE_* settings were deprecated in Django 1.8

您的设置为:

SILENCED_SYSTEM_CHECKS = ["1_8.W001"]

相关问题 更多 >