This article describes how to use the object list view in the Django framework. Django is one of the most famous popular Python web frameworks, if you need a friend, you can refer to direct_to_template. it is undoubtedly very useful, but the most useful part of Django's general view is to present data in the database. Because this application is so common, Django has many built-in general views to help you easily generate object lists and detailed views.
Let's take a look at one of the general views: The Object List View. Let's use Publisher in Chapter 5 as an example:
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, 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 to be compiled. 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))
If template_name is missing, an object name is automatically used in the object_list common view. In this example, the exported Template name will be "books/publisher_list.html". The books part is the name of the app that defines the model, and the publisher part is the lower-case name of the model.
This template is rendered according to the object_list variable contained in the context. this variable contains all the book objects. A very simple template looks like the following:
{% extends "base.html" %}{% block content %} Publishers
{% for publisher in object_list %}
- {{ publisher.name }}
{% endfor %}
{% endblock %}
(Example, we assume there is a base.html template .)
This is all you need to do. To use the common view cool feature, you only need to modify the parameter dictionary and pass it to the common view function. Appendix D is a complete reference for general views. the following sections in this chapter will cover some methods for customizing and extending general views.