DEV Community

Cover image for Naked in your codebase?

Naked in your codebase?

djangodoctor profile image Django Doctor Updated on ・3 min read

During my time as a GitHub code review bot I've seen many Django devs importing naked

Code review by

Django best practice tells us importing is bad and we should instead use from django.conf import settings, but why?

A simple answer is naked will not have the Django default values and can trigger a race condition, but there is more to it than that.

Overriding settings in tests is simplified too when using django.conf.settings as we can then use Django's modify_settings and django-pytest's settings fixture. This helps avoid unmaintainable flaky tests as one test's changes will not affect another because changes are reset after the test finishes.

To understand how that works we need to look deeper at what django.conf.settings is exactly.

Proxy for a swappable sources of truth

django.conf.settings is an instance of LazySettings. This object is a wrapper around a "holder" of the actual settings. During the normal running of your Django app, that holder ingests the values in the file defined by the environment variable DJANGO_SETTINGS_MODULE, which you will recognize from, or if you ever tried importing Django from the python shell without first setting that variable and getting the classic

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

As the name "lazy" implies, the values from DJANGO_SETTINGS_MODULE are not evaluated until they are interacted with. This is how we can import settings throughout our codebase with confidence that we will not get an error that the app is not ready yet.

So we can see, django.conf.settings is not the same thing as the file: django.conf.settings is a normally a proxy around your file, but not always.


During tests it's convenient to use very different values to those in your, or maybe the project does not have a (such as a third-party library).

For these cases we can explicitly call settings.cofigure(). When that happens the django.conf.settings's holder will be a UserSettingsHolder, and not interact with at all.

So there are a few great reasons to use from django.conf import settings instead of importing the directly:

  • You get Django's default values set
  • It simplifies safely overriding settings during tests
  • It avoid triggering app is not ready exceptions

Beware though that lowercase values in your are not exposed to django.conf.settings, but you can store those values in some other files so not a huge loss.

Does your codebase import directly?

Over time it's easy for tech debt to slip into your codebase. I can check that for you at, or can review your GitHub PRs:

Alt Text

Or try out Django refactor challenges.

Discussion (0)

Forem Open with the Forem app