DEV Community

Adam Hill
Adam Hill

Posted on

Checking Django Settings

I still keep coming back to this "the settings file still feels like a lot" concern in https://jvns.ca/blog/2026/01/27/some-notes-on-starting-to-use-django/#the-settings-file-still-feels-like-a-lot. What I was thinking about before was a LSP (Languge Server Protocol) which basically gives an IDE more metadata about the code it is parsing.

I have a prototype of that here: https://github.com/adamghill/django-lsp. It works pretty well for settings files, however I also wanted to approach this problem from another angle.

Could Python type hinting be used to alert the developer when they misconfigured a setting?

Type-checking settings

For example, a common one that has bit me in the past is something like this:

from os import getenv

DEBUG = getenv("DEBUG")
Enter fullscreen mode Exit fullscreen mode

If you run DEBUG=False python manage.py, your DEBUG setting will be a string, not a boolean. Then, something like if settings.DEBUG: will evaluate to True. Why? Because the string "False" is truthy. But, obviously, that is unintended and a bug.

If we define the types for all Django core settings, e.g. DEBUG: bool, DATABASES: list, etc. then we can at least validate that the setting is using the correct Python type.

One downside is that this doesn't help the developer when writing the code, i.e. this is not autocomplete in the IDE. However, it can be used as a runtime check as part of Django's check system. This would automatically alert the developer they are using the wrong type when runserver starts up.

Handling dictionaries

The above type check seems useful for simple settings, however another problem is that some settings are lists of dictionaries or dictionaries of dictionaries.

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": "db.sqlite3",
    }
},
Enter fullscreen mode Exit fullscreen mode

This can be very error-prone for developers because the keys like "ENGINE", "NAME", etc. are just strings. One approach here might be to provide helper methods which can guide the developer to use the correct functionality.

from django_settings_check import DATABASE

DATABASES = {
    "default": DATABASE(
        ENGINE="django.db.backends.sqlite3",
        NAME="db.sqlite3",
    )
},
Enter fullscreen mode Exit fullscreen mode

DATABASE is actually a function with defined args which means the IDE can autocomplete the acceptable options. And then it returns a dictionary which is what Django expects for settings.

There are a few other libraries for Django that provide cleaner ways to specify settings, but I have shied away from them in the past because they seem too "different" than regular Django. Maybe there is a way to implement this without changing too much about the default Django setup.

Looking for feedback about these ideas or if developers think this might be useful.

Top comments (0)