We may create custom constant variable in settings.py, eg : MEDIA_URL, STATIC_THEME, THEME_URL, etc. Then, we need to access this settings.py varible from Views and templates. Then here are what should we do :
Accessing custom variable in settings.py from views
We should import settings and use getattr(). For instance :
settings.py
1 | STATIC_THEME = ‘/static/theme’ |
views.py
1 2 3 | from django.conf import settings GET_STATIC_THEME = getattr(settings, ‘STATIC_THEME’, ‘default_value’) |
FYI, “default_value” is default if your CUSTOM_SETTINGS_VARIABLE not defined.
In this case, it mean STATIC_THEME default value.
Accessing custom variable settings.py in templates
We can accessing custom variable in settings.py by using Request Context , made Context Processor and “{% url from future %} in templates. First, we need to enable Context Processor in settings.py.
settings.py
1 2 3 4 5 6 7 8 9 | TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", ) |
Now we should use RequestContext in our views.py. Eg :
views.py
1 2 3 4 5 6 7 8 | from django.shortcuts import render def index(request): """Index page of Insurance plan.""" insurance_plan = InsurancePlan.objects.order_by(‘id’) return render(request, ‘insurance_plan/index.html’, {‘insurance_plan’: insurance_plan}) |
By using render, we can pass varible in Templates using Request Context.Then we should create custom context_processor to pass variable in settings.py into Request Context processors.
myapp/context_processors.py
1 2 3 4 5 | from django.conf import settings def common_settings(context): """Passing custom CONSTANT in Settings into RequestContext.""" return {‘STATIC_ACTIVE_THEME_URL’: settings.STATIC_ACTIVE_THEME_URL} |
your templates :
1 2 | {% load url from future %} {{ STATIC_ACTIVE_THEME_URL }} |