settings.py
MY_VAR = os.get("MY_VAR", False)
custom_middleware.py
from my_proj.settings import MY_VAR
from django.core.exceptions import MiddlewareNotUsed
class CustomMiddleware:
def _init_(self, get_response):
if MY_VAR == 'False':
raise MiddlewareNotUsed
self.get_response = get_response
def __call__(self, request):
if MY_VAR == 'True':
#My custom logic
return
response = self.get_response(request)
return response
test_custom_middleware.py
import os from unittest.mock import Mock
from api.middlewares.custom_middleware import CustomMiddleware
class TestLCustomMiddleware:
def test(self, settings):
request = Mock()
settings.MY_VAR = 'True'
assert settings.MY_VAR
with patch.dict('os.environ', {'MY_VAR': 'True'}):
assert 'MY_VAR' in os.environ
middleware = CustomMiddleware(get_response='response')
middleware(request)
In CustomMiddleware
I always get "False"
in MY_VAR
variable of settings. How can I set it up?
Updated.
Thanks to Philippe and Dharman. It works fine
custom_middleware.py
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
class CustomMiddleware:
def _init_(self, get_response):
if settings.MY_VAR == 'False':
raise MiddlewareNotUsed
self.get_response = get_response
def __call__(self, request):
if settings.MY_VAR == 'True':
#My custom logic
return
response = self.get_response(request)
return response
test_custom_middleware.py
from api.middlewares.custom_middleware import CustomMiddleware
from django.test import override_settings
class TestLCustomMiddleware:
@override_settings(MY_VAR="True")
def test(self):
request = Mock()
middleware = CustomMiddleware(get_response='response')
middleware(request)
CodePudding user response:
As explaned in Django documentation, you should import your setting using :
from django.conf import settings
if settings.MY_VAR:
# Do something
"django.conf.settings" isn’t a module, it’s an object. So importing individual settings is not possible. This example below won't work properly :
from django.conf.settings import MY_VAR
Furthermore, it's not recommended to change setting during Runtime :
from django.conf import settings
settings.DEBUG = True # Don't do this!
Instead you should try using override_settings() or modify_settings(). For example :
from django.test import TestCase, override_settings
class TestLCustomMiddleware(TestCase):
@override_settings(MY_VAR=True) # without quote
def test(self):
...