Sometimes you will find that the view functions you write are very similar, only a little bit different. For example, you have two views, their content is consistent, except that they use a different template:
# urls.pyfrom django.conf.urls.defaults Import *from mysite Import viewsurlpatterns = Patterns (', (R ' ^foo/$ ', views . Foo_view), (R ' ^bar/$ ', Views.bar_view),) # Views.pyfrom django.shortcuts Import Render_to_responsefrom Mysite.models Import mymodeldef Foo_view (Request): m_list = MyModel.objects.filter (is_new=true) return Render_to_response (' template1.html ', {' m_list ': m_list}) def bar_view (request): m_list = MyModel.objects.filter ( Is_new=true) return render_to_response (' template2.html ', {' m_list ': m_list})
We do repetitive work in this code, not concise enough. At first you might want to use the same view for all two URLs, use parentheses to capture the request in the URL, and then check in the view and decide which template to use to remove redundancy from the code, like this:
# urls.pyfrom django.conf.urls.defaults Import *from mysite Import viewsurlpatterns = Patterns (', (R ' ^ (foo)/$ ', Views.foobar_view), (R ' ^ (bar)/$ ', Views.foobar_view),) # Views.pyfrom django.shortcuts Import render_to_ Responsefrom mysite.models Import mymodeldef foobar_view (Request, URL): m_list = MyModel.objects.filter (is_new= True If url = = ' foo ': template_name = ' template1.html ' elif url = = ' bar ': template_name = ' Template2.html ' return Render_to_response (template_name, {' M_list ': m_list})
The problem with this solution is the old drawback of coupling your URLs into your code. If you're going to change/foo/to/fooey/, then you have to remember to alter the code in the view.
An elegant solution to an optional URL configuration parameter: urlconf Each pattern can contain a third data: A Dictionary of keyword parameters:
With this concept in place, we can rewrite our current example:
# urls.pyfrom django.conf.urls.defaults Import *from mysite Import viewsurlpatterns = Patterns (', (R ' ^foo/$ ', views . Foobar_view, {' template_name ': ' template1.html '}), (R ' ^bar/$ ', Views.foobar_view, {' Template_name ': ' Template2.html '}) # Views.pyfrom django.shortcuts import render_to_responsefrom mysite.models import MyModeldef Foobar_view (Request, Template_name): m_list = MyModel.objects.filter (is_new=true) return render_to_ Response (Template_name, {' M_list ': m_list})
As you can see, in this example, urlconf specifies the template_name. And the view function treats it as another parameter.
This technique of using additional urlconf parameters gives you a good way to pass additional information to the view function at minimal cost.