How to suppress the deprecation warnings in Django?

Question:

Every time I’m using the django-admin command — even on TAB–completion — it throws a RemovedInDjango19Warning (and a lot more if I use the test command). How can I suppress those warnings?

I’m using Django 1.8 with Python 3.4 (in a virtual environment). As far as I can tell, all those warnings come from libraries not from my code.

Examples

Here are some examples:

  • …/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)

Update

Since Django version 1.11 (release notes) deprecating warnings are no longer loud by default. So I guess this won’t be an issue anymore, since 1.11 is the last version to support Python 2 and also features long-term support.

Asked By: Brutus

||

Answers:

In manage.py, add this to the top line —

#!/usr/bin/env PYTHONWARNINGS=ignore python

This will suppress all warnings, which I agree can in some situations be undesirable if you’re using a lot of third party libraries.

Disclaimer: Recommended only after you’ve already seen the warnings at least 1,000 too many times already, and should be removed when you upgrade Django.

Note: this may have some undesirable effects on some platforms, eg swallowing more output than just warnings.

Answered By: s29

This standart django script add TAB–completion for you bash – https://github.com/django/django/blob/master/extras/django_bash_completion

PYTHONWARNINGS is not defined – error in console. Add export PYTHONWARNINGS=”ignore” and unset PYTHONWARNINGS in _django_completion()

Original function:

_django_completion()
{
    COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" 
                   COMP_CWORD=$COMP_CWORD 
                   DJANGO_AUTO_COMPLETE=1 $1 ) )
}

My version. Do not break the basic behavior in other cases.

_django_completion()
{
    export PYTHONWARNINGS="ignore"
    COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" 
                   COMP_CWORD=$COMP_CWORD 
                   DJANGO_AUTO_COMPLETE=1 $1 ) )
    unset PYTHONWARNINGS
}
Answered By: Forester

Adding a logging filter to settings.py can suppress these console warnings (at least for manage.py commands in Django 1.7, Python 3.4).

A filter can selectively suppress warnings. The following code creates a new “suppress_deprecated” filter for the console and appends it to the default logging filters. Add this block to settings.py to configure the LOGGING variable:

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])

The ‘mysite.settings.SuppressDeprecated’ string needs to change if the root website module (or filter location and/or name) is different.

Answered By: Fred Schleifer

For some reason the solution provided by Fred Schleifer didn’t work for me in Django 1.9, so I had to find a different solution.

In settings.py, I set up a custom LOGGING_CONFIG function:

LOGGING_CONFIG = 'my_project.logging_utils.configure'

Then I defined my custom my_project.logging_utils module like so:

from logging.config import dictConfig
import warnings
from django.utils.deprecation import RemovedInDjango110Warning

IGNORE_DJANGO_110_WARNINGS = {
    # This is a specific warning raised by a third-party library.
    r'rest_framework_swagger.urls': r'django.conf.urls.patterns() is deprecated.*'
}

def configure(settings):
    dictConfig(settings)
    for module, message in IGNORE_DJANGO_110_WARNINGS.items():
        warnings.filterwarnings(
            action='ignore',
            category=RemovedInDjango110Warning,
            module=module,
            message=message
        )

The IGNORE_DJANGO_110_WARNINGS dict contains a mapping from module names to regular expressions of warnings raised by them. I chose to be very specific in the kinds of warnings I suppressed, as I still wanted to see ones that I didn’t expect. As individual third-party libraries are updated, I’ll remove their associated entries from the dict.

Answered By: Atul Varma

In django 1.7, a new setting was introduced SILENCED_SYSTEM_CHECKS to suppress warnings

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

Here is a list of all the checks to suppress
Example:

If you wish to suppress the TEMPLATES_ warning,

The standalone TEMPLATE_* settings were deprecated in Django 1.8

your settings would be:

SILENCED_SYSTEM_CHECKS = ["1_8.W001"]
Answered By: karthikr

Nothing of the above have worked for me, django 1.9. I fixed this by adding the following lines to settings.py:

import logging

def filter_deprecation_warnings(record):
     warnings_to_suppress = [
        'RemovedInDjango110Warning'
    ]

    # Return false to suppress message.
    return not any([warn in record.getMessage() 
         for warn in warnings_to_suppress])

warn_logger = logging.getLogger('py.warnings')
warn_logger.addFilter(filter_deprecation_warnings)
Answered By: Ivan Vigasin

Django puts warnings through the standard python warnings module. If your python project throws warnings and they’re “acceptable” for the moment, just use warnings.filterwarnings() or warnings.simplefilter(). I’m not sure where the “best” place for these are, but I’ve dropped them into my common_settings.py file (For me, this is a unchanging, checked-in file, that is imported by local_settings.py).

Eg:

warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning, module='django.template.utils', lineno=37)

Alas the comment about silencing the system checks won’t work, here, since your example isn’t throwing a system-check error.

Answered By: Chris Cogdon

While reviewing deprecation warnings in other dependencies of my Django 1.8 project, using

python -Wd manage.py runserver

, I was able to filter out Django deprecation warnings by temporarily adding

import warnings
from django.utils.deprecation import RemovedInDjango110Warning
warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning)

to my settings.py (can presumably be in any module that’s loaded at startup). I couldn’t figure out how to include the filter as an extra -W option, i.e.

python -Wd -Wi::RemovedInDjango110Warning manage.py runserver

resulted in Invalid -W option ignored: unknown warning category: 'RemovedInDjango110Warning'.

Answered By: Donny Winston
# in settings.py
import warnings
from django.utils.deprecation import RemovedInDjango20Warning

DEBUG = True

if DEBUG:
    warnings.simplefilter('default')
    warnings.filterwarnings('ignore', category=RemovedInDjango20Warning)
    # use it if you annoyed by DeprecationWarning
    warnings.filterwarnings('ignore', category=DeprecationWarning)
Answered By: madjardi

For a quick command-line interface only solution, preface manage.py with python -W ignore when executing, as in:

python -W ignore manage.py runserver

-or-

python -W ignore manage.py shell_plus

-or-

python -W ignore manage.py makemigrations

This is working for me now, to suppress all of the Django 1.10 deprecation warnings while running Django 1.9.

Answered By: Mark Chackerian

I’ll leave this for newcomers:

As for django 1.11 deprecating warnings are no longer loud by default. To activate them run python -Wd manage.py runserver for example.

source

Answered By: Willemoes

I currently encounter this same issue when using Django 1.8. Instead of completely suppress those warnings, we decide to show them only in DEBUG mode.

We can add console handler in logging settings and use this handler to catch py.warnings. Here is the code snippet,

'filters': {
    'require_debug_true': {
        '()': 'django.utils.log.RequireDebugTrue'
    },
    ...
},
'handlers': {
    'console': {
        'level': 'DEBUG',
        'filters': ['require_debug_true'],
        'class': 'logging.StreamHandler',
        'formatter': 'standard',
    },
    ...
},
'loggers': {
    'py.warnings': {
        'handlers': ['console', ],
        'level': 'INFO',
        'propagate': False
    },
    ...
}

The complete Django settings file: https://github.com/haiwen/seahub/blob/21c827c68047e13700fe102d22a3f5515b22af89/seahub/settings.py#L484

Answered By: xiez

Time to add another one suggestion here, which worked for me. Django 3.2, but should work on any version.

What worked for me is assuming that the developers would be clever enough to output these to python stderr, not stdout. They were!

So…, just redirect stderr to via a standard bash 2>/dev/null

django-admin findstatic teststatic.css 2>/dev/null
Found 'teststatic.css' here:
  /Users/me/kds2/py2/bemyerp/websec/static/websec/nodelinks/teststatic.css
  /Users/me/kds2/py2/bemyerp/dist/teststatic.css

Of course, bear in mind your context and what this redirection does: suppressing ANY error message. For example, if django-admin is missing, that error message will also disappear (run missing-django-admin findstatic teststatic.css 2>/dev/null to see the effect).

what I was trying to filter out…

    HINT: Use django.db.models.JSONField instead.
pssystem.TagType: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    HINT: Configure the DEFAULT_AUTO_FIELD setting or the AppConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
Found 'teststatic.css' here:
  /Users/me/kds2/py2/bemyerp/websec/static/websec/nodelinks/teststatic.css
  /Users/me/kds2/py2/bemyerp/dist/teststatic.css

Things tried without success:

(I am not saying these never work, only that they didn’t filter the particular messages I was getting and wanted to avoid, in my environment.

python -W ignore  manage.py findstatic teststatic.css
PYTHONWARNINGS=ignore django-admin findstatic teststatic.css
PYTHONWARNINGS=ignore python manage.py findstatic teststatic.css
python -Wd manage.py findstatic teststatic.css

env: Django 3.2, using Python 3.10 with virtualenv

Answered By: JL Peyret
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.