I would like to know how to pass a variable to all my templates, without repeating the same code on every method in my views.py file?
In the example below I would like to make categories (an array of category objects) available to all templates in the web app.
Eg: I would like to avoid writing 'categories':categories on every method. Is it possible?
One view method
def front_page(request):
categories = Category.objects.all()
if is_logged_in(request) is False:
return render_to_response('users/signup.html', {'is_logged_in': is_logged_in(request), 'categories':categories}, context_instance=RequestContext(request))
else:
return render_to_response('users/front_page.html', {'is_logged_in': is_logged_in(request), 'categories':categories},context_instance=RequestContext(request))
Another view method
def another_view_method(request):
categories = Category.objects.all()
return render_to_response('eg/front_page.html', {'is_logged_in': is_logged_in(request), 'categories':categories},context_instance=RequestContext(request))
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
What you want is a context processor, and it’s very easy to create one. Assuming you have an app named custom_app, follow the next steps:
- Add
custom_apptoINSTALLED_APPSinsettings.py(you’ve done it already, right?); - Create a
context_processors.pyintocustom_appfolder; -
Add the following code to that new file:
def categories_processor(request): categories = Category.objects.all() return {'categories': categories} -
Add
context_processors.pytoTEMPLATE_CONTEXT_PROCESSORSinsettings.pyTEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", )
And now you can use {{categories}} in all the templates 😀
As of Django 1.8
To add a TEMPLATE_CONTEXT_PROCESSORS, in the settings you must add the next code:
TEMPLATES[0]['OPTIONS']['context_processors'].append("custom_app.context_processors.categories_processor")
Or include that string directly in the OPTIONS.context_processors key in your TEMPLATES setting.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0