Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[New Rule][Django] Verify that settings is correctly imported #12200

Closed
bastian-wattro opened this issue Jul 5, 2024 · 2 comments
Closed

[New Rule][Django] Verify that settings is correctly imported #12200

bastian-wattro opened this issue Jul 5, 2024 · 2 comments
Labels
rule Implementing or modifying a lint rule

Comments

@bastian-wattro
Copy link

I'd like to add a rule for Django projects. I'm not quite sure about where to add it (If backwards capability was not an issue, I would add it to DJ)

What it could do

Verify that settings is correctly imported from django.conf.

An unsafe fix could exist, as some code might depend on the side effects of importing the module (even though import side-effects are considered poor practice).

Why is this bad?

The Django Docs state that one should import settings from django.conf.
It is an object (not a module) that is safe to access. Importing settings directly from the project could trigger side-effects.
Also, django.conf.settings abstracts the concepts of default settings and site-specific settings; it presents a single interface. It also decouples the code that uses settings from the location of the settings.

Example

Incorrect:

from myproject import settings

Use instead:

from django.conf import settings

I'm looking forward to your feedback.

@MichaReiser MichaReiser added the rule Implementing or modifying a lint rule label Jul 11, 2024
@q0w
Copy link

q0w commented Jul 23, 2024

You can already do this with banned-api (no auto fix)

@bastian-wattro
Copy link
Author

Nice.

Add this to your pyproject.toml and replace myproject with the name of your project.
drop tool.ruff. if you're using ruff.toml

[tool.ruff]
lint.select = [
   
   "TID251", # tidy imports
]

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"myproject.settings".msg = "See https://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code. Use 'from django.conf import settings' instead."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule Implementing or modifying a lint rule
3 participants