Main MVT issue in Django

I have a Django site as follows:

  • the site has several views
  • Each view has its own template for displaying its data.
  • each template extends the base template
  • the base template is the base of the site, has all the JS / CSS and the main layout

So still so good. So, now we have the main site manager (which exists in the base template), and it is common to all views.

But now I want to make it dynamic and add dynamic data to it. From what point of view am I doing this? All my views are basically render_to_response('viewtemplate.html', someContext) . So how to add a general look to the base template?

Obviously, I will not duplicate the common code for each individual view ...

I think that I don’t have something fundamental at the heart of Django MVT.

+6
python django django-templates
source share
3 answers

You want to use context_instance and RequestContext s.

First add views.py to the top of the page:

 from django.template import RequestContext 

Then refresh all your views to look like this:

 def someview(request, ...) ... return render_to_response('viewtemplate.html', someContext, context_instance=RequestContext(request)) 

In settings.py add:

 TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', ... 'myproj.app.context_processors.dynamic', 'myproj.app.context_processors.sidebar', 'myproj.app.context_processors.etc', ) 

Each of these context_processors is a function that takes a request object and returns a context in the form of a dictionary. Just put all the functions in context_processors.py inside the corresponding application. For example, a blog may have a sidebar with a list of recent posts and comments. context_processors.py will simply define:

 def sidebar(request): recent_entry_list = Entry.objects... recent_comment_list = Comment.objects... return {'recent_entry_list': recent_entry_list, 'recent_comment_list': recent_comment_list} 

You can add as much or less as you want.

See the Django Template Docs for more details.

+7
source share

Context processors and RequestContext (see Tyler's answer) is a way to use the data that is used for each page load. For data that may be required for different views, but not for all (especially data that is not related to the main purpose of the view, but appears as something like a side navigation bar), it often makes sense to define a custom tag template for data extraction.

+2
source share

or use the general view as they automatically convey the request context.

A simple simple generic general view can be used to avoid the need for import / transfer in the context of the request.

-one
source share

All Articles