We are updating our application from Django 1.6 to 1.7.
We see a lot of these message:RemovedInDjango18Warning
Is there a way to filter them? They get emitted during importing.
We tried warnings.filterwarnings('ignore', '...')
but the warnings get emitted before we call warnings.filterwarnings()
.
How can I filter these warnings which happen during importing?
To silence it only when you run manage.py
, add these lines after import sys
:
# ...
import sys
if not sys.warnoptions:
sys.warnoptions += [None]
# ...
If you also want to silence it from your WSGI server (i.e. Apache), update your_project/wsgi.py
and add the following lines after import os
:
# ...
import os
import sys
if not sys.warnoptions:
sys.warnoptions += [None]
# ...
The reason this works is because of how django.utils.log.configure_logging()
handles it:
def configure_logging(logging_config, logging_settings):
if not sys.warnoptions:
# Route warnings through python logging
logging.captureWarnings(True)
# RemovedInNextVersionWarning is a subclass of DeprecationWarning which
# is hidden by default, hence we force the "default" behavior
warnings.simplefilter("default", RemovedInNextVersionWarning)
# ...
It's deliberately called early in the boot process as part of django.setup()
, which explains why errors were emitted before you were able to silence them further down the stack.
Adding a new element to sys.warnoptions
forces it to evaluate to True
, bypassing the logic. This is harmless since it's only used during python startup when loaded by the warnings
module.
RemovedInNextVersionWarning
is just an alias for RemovedInDjango18Warning
in Django 1.7. It is set to RemovedInDjango19Warning
in 1.8, and so on for future versions -- this code should be future proof for this type of DeprecationWarning
.
Note that sys.warnoptions
is normally set during python startup based on the -W
argument when calling python. Therefore, a simple way to just silence the warnings when you use the dev server is python -W123 manage.py runserver
. This requires no modification of files, but does result in a single harmless warning at startup since 123
is just a placeholder and not a valid warning action.
Another way is python -Wi::DeprecationWarning manage.py runserver
, though this will ignore ALL DeprecationWarning
s, including possibly ones of interest which are not RemovedInDjango18Warning
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With