Skip to content

Commit 8196b1f

Browse files
committed
Set undefined env variables using CLI arguments
Both `DJANGO_SETTINGS_MODULE` and `DJANGO_CONFIGURATION` are required for `django.configurations.importer` to install, else it throws an exception. If the `importer` is not installed, `django.setup()` fails on `configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)` when trying to access uninitialized settings. fixes pylint-dev#309 (pylint-dev#309 (comment)) fixes pylint-dev#325 might relate to pylint-dev#362
1 parent 6c1e67e commit 8196b1f

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,4 @@
2020
* [naquiroz](https://github.com/naquiroz)
2121
* [john-sandall](https://github.com/john-sandall)
2222
* [dineshtrivedi](https://github.com/dineshtrivedi)
23+
* [TheAfroOfDoom](https://github.com/TheAfroOfDoom)

pylint_django/checkers/foreign_key_strings.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from __future__ import absolute_import
22

3+
import os
4+
35
import astroid
6+
from configurations import importer
47
from pylint.checkers import BaseChecker
58
from pylint.checkers.utils import check_messages
69
from pylint.interfaces import IAstroidChecker
@@ -41,6 +44,15 @@ class ForeignKeyStringsChecker(BaseChecker):
4144
"help": "A module containing Django settings to be used while linting.",
4245
},
4346
),
47+
(
48+
"django-configuration",
49+
{
50+
"default": None,
51+
"type": "string",
52+
"metavar": "<django configuration>",
53+
"help": "The configuration for Django to use while linting.",
54+
},
55+
),
4456
)
4557

4658
msgs = {
@@ -89,6 +101,32 @@ def open(self):
89101
try:
90102
import django # pylint: disable=import-outside-toplevel
91103

104+
if (
105+
os.environ.get("DJANGO_SETTINGS_MODULE") is None
106+
or os.environ.get("DJANGO_CONFIGURATION") is None
107+
):
108+
try:
109+
os.environ.setdefault(
110+
"DJANGO_SETTINGS_MODULE",
111+
os.environ.get("DJANGO_SETTINGS_MODULE")
112+
or self.config.django_settings_module,
113+
)
114+
os.environ.setdefault(
115+
"DJANGO_CONFIGURATION",
116+
os.environ.get("DJANGO_CONFIGURATION")
117+
or self.config.django_configuration,
118+
)
119+
except TypeError as ex:
120+
missing_module = ""
121+
if self.config.django_settings_module is None:
122+
missing_module = "DJANGO_SETTINGS_MODULE"
123+
else:
124+
missing_module = "DJANGO_CONFIGURATION"
125+
raise RuntimeError(
126+
f"{missing_module} required to initialize Django project settings"
127+
) from ex
128+
importer.install()
129+
92130
django.setup()
93131
from django.apps import ( # noqa pylint: disable=import-outside-toplevel,unused-import
94132
apps,

0 commit comments

Comments
 (0)