[Django]-Django: how to extend settings.py?

2đź‘Ť

âś…

You should import local settings module

import settings
settings.TEMPLATE_CONTEXT_PROCESSORS += ['portal.context_processors.login_form_processor']
👤H1D

2đź‘Ť

You can have a “standard settings” and can import this settings on settings.py of your project, how:

On your standard settings:

# settings_standard.py
TEMPLATE_CONTEXT_PROCESSORS = (
    'context_one',
    'context_two'
)

And on your project settings:

# project settings.py
import settings_standard.py

TEMPLATE_CONTEXT_PROCESSORS += (
    'context_three',
    'context_four'
)

Attention for += on second TEMPLATE_CONTEXT_PROCESSORS. 🙂

👤Rael Max

1đź‘Ť

Here’s how I extended the django-rest-framework throttling rates, so I could have different values in development and production.

base.py

# Django rest framework
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        #'rest_framework.authentication.BasicAuthentication',
        #'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '10/minute'
    },
}

production.py

from .base import *

REST_FRAMEWORK['DEFAULT_THROTTLE_RATES'] = {
    'anon': '1000/day',
    'user': '30/minute'
}
👤Little Brain

0đź‘Ť

It depends on whether or not your TEMPLATE_CONTEXT_PROCESSORS is already a list or a tuple. If it’s a list then that will work, if it’s a tuple then you’ll get an error about trying to add a list and a tuple together.

You could do, to be sure that it works…

from django.conf import settings
tpl_ctx_prcs = list(settings.TEMPLATE_CONTEXT_PROCESSORS)
tpl_ctx_prcs.append('portal.context_processors.login_form_processor')
settings.TEMPLATE_CONTEXT_PROCESSORS = tuple(tpl_ctx_prcs)

But whether or not this actually does what you want it to do–i.e., add that template context processor so that it actually get’s called depends on where and when you are doing this.

Is there any reason why you wouldn’t want just add this to your settings.py file? Even if you only need the extra context within a single app it’s not really “bad” to have it appear in your other apps as well.

👤Chris W.

Leave a comment