Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between override_settings and modify_settings in Django?

Tags:

python

django

Django's docs on testing tools mention both the @override_settings and the @modify_settings decorators for usage in tests, but it is unclear from the docs (at least to me) what is the difference between them.

So, what is it?

like image 465
Chris Avatar asked Mar 20 '17 14:03

Chris


1 Answers

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.

like image 170
Jamie Counsell Avatar answered Oct 16 '22 15:10

Jamie Counsell