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 our GitHub code review bot spots this issue in your pull request it gives this advice:

django-doctorbotsuggested changes just now
urls.py
1
+
from django.conf import settings
2
+
from django.contrib import admin
3
+
4
+
	
5
+
urlpatterns = [...]
6
+
	
7
+
if settings.DEBUG:
Suggested changes
-
if settings.DEBUG:
+
if settings.FEATURE_ADMIN_ENABLED:
Expand 2 lines ...
Commit suggestion

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
8
+
    # not exposing admin to prod so it can't be hacked
9
+
    urlpatterns.append(path('admin/', admin.site.urls))
Update urls.py
We're your Django code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review 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 Code Review Doctor.