Direct_to_template is undoubtedly very useful, but the most useful part of the Django Common view is to render the data in the database. Because this app is so common, Django has a lot of built-in general-purpose views to help you easily generate lists and detail views of objects.
Let's take a look at one of the common Views: Object List view. We use Publisher in the fifth chapter to illustrate:
Class Publisher (models. Model): name = models. Charfield (max_length=30) address = models. Charfield (max_length=50) City = models. Charfield (max_length=60) state_province = models. Charfield (max_length=30) country = models. Charfield (max_length=50) website = models. Urlfield () def __unicode__ (self): return Self.name class Meta: ordering = [' name ']
To create a list page for all publishers, we use the following URL configuration:
From django.conf.urls.defaults import *from django.views.generic import list_detailfrom mysite.books.models Import Publisherpublisher_info = { ' queryset ': Publisher.objects.all (),}urlpatterns = Patterns (", (R ' ^publishers/ $ ', list_detail.object_list, Publisher_info))
This is all the Python code that you want to write. Of course, we also need to write a template. We can explicitly tell the Object_list view which template to use by including a Template_name key in the extra-parameter dictionary:
From django.conf.urls.defaults import *from django.views.generic import list_detailfrom mysite.books.models Import Publisherpublisher_info = { ' queryset ': Publisher.objects.all (), * * ' template_name ': ' Publisher_list_ Page.html ', **}urlpatterns = Patterns (', (R ' ^publishers/$ ', List_detail.object_list, Publisher_info))
In the absence of Template_name, the Object_list Universal view will automatically use an object name. In this example, the derived template name will be "books/publisher_list.html", where the books part is the name of the app that defines the model, and the Publisher section is the lowercase of the model name.
This template will be rendered according to the variable object_list contained in the context, which contains all the book objects. A very simple template looks like this:
{% extends "base.html"%} {% block content%} Publishers
{% for publisher in object_list%}
- {{Publisher.name}}
{% endfor%}
{% Endblock%}
(Note that here we assume that there is a base.html template.) )
That's all you have to do. To use the common view cool features only need to modify the parameter dictionary and pass it to the common view function. Appendix D is a complete reference for a common view; the next chapters in this chapter will cover some of the ways to customize and extend a common view.