I have a Django website as follows:
- site has several views
- each view has its own template to show its data
- each template extends a base template
- base template is the base of the site, has all the JS/CSS and the basic layout
So up until now it’s all good. So now we have the master head of the site (which exists in the base template), and it is common to all the views.
But now I want to make it dynamic, and add some dynamic data to it. On which view do I do this? All my views are basically render_to_response('viewtemplate.html', someContext). So how do add a common view to a base template?
Obviously I will not duplicate the common code to each separate view…
I think I’m missing something fundamental in the MVT basis of Django.
You want to use
context_instanceandRequestContexts.First, add at the top of your
views.py:Then, update all of your views to look like:
In your
settings.py, add:Each of these
context_processorsis a function takes therequestobject and returns a context in the form of a dictionary. Just put all the functions incontext_processors.pyinside the appropriate app. For example, a blog might have a sidebar with a list of recent entries and comments.context_processors.pywould just define:You can add as many or as few as you like.
For more, check out the Django Template Docs.