15👍
override_settings
will completely change the object stored in side the setting. That is, the original value will be destroyed. modify_settings
will modify the existing object in place. This works by taking the append
, prepend
, and remove
parameters. The object you’re seeing in the documentation is not the MIDDLEWARE
object, it’s a list of steps to perform on the MIDDLEWARE
object to modify it. For example, given the following MIDDLEWARE
defined in settings.py
:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
If you use:
@modify_settings(MIDDLEWARE={
'append': 'django.middleware.cache.FetchFromCacheMiddleware',
'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
'remove': [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
],
})
It yields the final settings:
MIDDLEWARE=[
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware'
]
The same result with override_settings
would require the entire resulting object above.
The problem here is obvious. If we change the original MIDDLEWARE
settings in settings.py
, we will have to update our test. If we use modify_settings
, we would likely still be good to go.
I agree that the docs aren’t clear because it doesn’t really make it clear that 'append'
is a special keyword, for example.