Can I access constants in settings.py from templates in Django? Django provides access to certain, frequently-used settings constants to the template such as settings.MEDIA_URL
and some of the language settings if you use django’s built in generic views or pass in a context instance keyword argument in the render_to_response shortcut function. Here’s an example of each case:
1 2 3 4 5 6 7 8 9 | from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic.simple import direct_to_template def my_generic_view(request, template='my_template.html'): return direct_to_template(request, template) def more_custom_view(request, template='my_template.html'): return render_to_response(template, {}, context_instance=RequestContext(request)) |
These views will both have several frequently used settings like settings.MEDIA_URL
available to the template as {{ MEDIA_URL }}, etc.
If you’re looking for access to other constants in the settings, then simply unpack the constants you want and add them to the context dictionary you’re using in your view function, like so:
1 2 3 4 5 6 | from django.conf import settings from django.shortcuts import render_to_response def my_view_function(request, template='my_template.html'): context = {'favorite_color': settings.FAVORITE_COLOR} return render_to_response(template, context) |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.