Django @override_settings does not allow to use a dictionary?

I'm new to Python decorators, so maybe I am missing something simple, here is my situation:

This works for me:

def test_something(self): settings.SETTING_DICT['key'] = True #no error ... 

But this leads to the fact that the SyntaxError: keyword cannot be an expression:

 @override_settings(SETTING_DICT['key'] = True) #error def test_something(self): ... 

Just to be clear, the normal use of override settings works:

 @override_settings(SETTING_VAR = True) #no error def test_something(self): ... 

Is there a way to use the decorator using the settings dictionary, or am I doing something wrong?

Thanks in advance!

+6
source share
2 answers

You must override the entire dict:

 @override_settings(SETTING_DICT={'key': True}) def test_something(self): ... 

Or you can use override_settings as a context manager:

 def test_something(self): value = settings.SETTING_DICT value['key'] = True with override_settings(SETTING_DICT=value): ... 
+10
source

I also did not want to redefine all the text, so I copied the corresponding dictionary from the settings object and simply changed the attribute that interests me:

 import copy from django.conf import settings settings_dict = deepcopy(settings.SETTINGS_DICT) settings_dict['key1']['key2'] = 'new value' @override_settings(SETTINGS_DICT=settings_dict) def test_something(self): pass 

This is suitable for my purposes, but if you want to make it more widely used, you can write a short function with several arguments that can do something like this dynamically.

Note: I tried using settings.SETTINGS_DICT.copy() instead of deepcopy(settings.SETTINGS_DICT) but it seems to override the setting globally for all tests ...

0
source

Source: https://habr.com/ru/post/970822/


All Articles