Using settings.DEBUG as a feature flag hinders testing

Your code is harder to test in isolation because the value of settings.DEBUG affects other Django behaviours including error handling. Consider using a feature flag instead.

settings.DEBUG is for switching whether Django should run in debug mode. This is a switch to control the behavior of the framework, not your code. Using this for also controlling the behaviour of the application code you built on top of the framework makes the codebase harder to maintain and test.

For a concrete example, settings.DEBUG = True shows detailed error pages for use during local development, while settings.DEBUG = False can result in the error instead being emailed to settings.ADMINS. Do you want to cause either of those behavioural changes while testing your code? Probably not, as this is inconvenient and also goes against the principle of least surprise.

Twelve factor App suggests aiming for dev/prod parity. Using settings.DEBUG to control which block of code your application runs prevents dev/prod parity because most devs will not test or run their local environment with DEBUG = False. To solve this instead consider adding a feature flag specifically for this one check, which you can switch easily during unit tests and with none of the other side effects inherent with settings.DEBUG.

If we spot this issue in your GitHub pull request we give this advice:

urls.pymaintainabilitymedium
from django.conf import settings
from django.contrib import admin
	
urlpatterns = [...]
	
if settings.DEBUG:
    # not exposing admin to prod so it can't be hacked
    urlpatterns.append(path('admin/', admin.site.urls))

Your code is harder to test in isolation because the value of settings.DEBUG affects other Django behaviours including error handling. Consider using a feature flag instead.

Read more
Protect your pull requests from over 40 types of common Django technical debts with our GitHub code review bot.

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code checking-settings-debug in your pyproject.toml file.

Read more about configuring Django Doctor.