01- Introduction
General view of the development in view of the wording and common mode abstracted, so you can quickly write a small amount of code to implement common data view. Display a list of objects is one such task.
Django generic views comes to achieve the following functions: 1, lists the details of a single object and display the object. If you create an application management meetings, then TalkListView and Reg- isteredUserListView is the list view. A presentation of a page that details view. 2 , showing the date based on the object to display as the date archive page (with details), and the "latest" page. 3, allowing users to create, update, and delete objects - or need the authorization will do.
# models.py from django.db import models 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() class Meta: ordering = ["-name"] def __str__(self): return self.name class Author(models.Model): salutation = models.CharField(max_length=10) name = models.CharField(max_length=200) email = models.EmailField() headshot = models.ImageField(upload_to='author_headshots') def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author') publisher = models.ForeignKey(Publisher) publication_date = models.DateField()
General view of the object -ListView 02-
# views.py from django.views.generic import ListView from books.models import Publisher class PublisherList(ListView): Model = Publisher # specify the corresponding template template_name = Books / publisher_list.html # urls.py from django.conf.urls import url from books.views import PublisherList urlpatterns = [ url(r'^publishers/$', PublisherList.as_view()), ]
# When you render this template, there is a context variable named object_list, its value is subject to all publishers. The extends% { " base.html " % } {% block content %} <h2>Publishers</h2> <ul> {% for publisher in object_list %} <li>{{ publisher.name }}</li> {% endfor %} </ul> {% endblock %}
03- specify the template name of the context - context_object_name
# The default is object_name class PublisherList(ListView): model = Publisher context_object_name = 'my_favorite_publishers'
04- provide additional context variables - get_context_data
Typically, information in addition to the generic view, would also show some additional information. But how to get additional information about it in the template?
The answer is an extension ListView, DetailView, etc., to achieve their own get_context_data method.
The default implementation only the display of template objects, but you can cover, provide more information:
from django.views.generic import DetailView from books.models import Publisher, Book class PublisherDetail(DetailView): model = Publisher DEF get_context_data (Self, ** kwargs): # to call the original implementation, acquiring context context = Super (PublisherDetail, Self) .get_context_data (** kwargs) # to query all books constitute a collection of add context to context [ ' book_list ' ] = Book.objects.all () return context
Note: By default, the contextual data for all the parent class will get_context_data the combined current class. If you do not want to adjust this behavior in the context of a subclass, to call get_context_data on the superclass.
If the class does not define two keys in the same context, the results thus obtained as expected.
However, if you try to cover the key superclass set (after calling super), when the subclass want to cover all superclass, subclass must explicitly set the key after calling super.
05- subset of display objects - queryset
from django.views.generic import DetailView from books.models import Publisher class PublisherDetail(DetailView): context_object_name = ' Publisher ' # Model = Publisher actually queryset = Publisher.objects.all () concise form. # However, the use queryset can filter the list of objects, further specify the object you want to view in the view. Such as: filtering queryset = Publisher.objects.all ()
from django.views.generic import ListView from books.models import Book class BookList(ListView): queryset = Book.objects.order_by('-publication_date') context_object_name = 'book_list'
06- dynamic filtration - get_queryset ()
Requirements: object list page URL filtering based on specified key. Solution: covering the ListView get_queryset () method. The default implementation is to return queryset attribute values, but you can add more logic. Called when the view class-based, a lot of useful things in the store to the self, in addition to the request (self.request), there are parameters depending on the position (self.args) URL configuration and capture of key parameters (self.kwargs) . # urls.py from django.conf.urls import url from books.views import PublisherBookList urlpatterns = [ url(r'^books/([\w-]+)/$', PublisherBookList.as_view()), ] # views.py from django.shortcuts import get_object_or_404 from django.views.generic import ListView from books.models import Book, Publisher class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.args[0]) return Book.objects.filter(publisher=self.publisher)
If desired, the current user can use self.request.user by filtration or other implement more complex logic. At the same time, we can also add objects to the Press context for template:
DEF get_context_data (Self, ** kwargs): # to achieve the original call, obtain context context = Super (PublisherBookList, Self) .get_context_data (** kwargs) # add objects Press context [ ' Publisher ' ] = self.publisher return context # # perform additional operations
07- to do before or after calling the generic view extra work - get_object ()
There is a model assumptions Author last_accessed field for recording the last time the author's information was viewed:
# models.py from django.db import models class Author(models.Model): salutation = models.CharField(max_length=10) name = models.CharField(max_length=200) email = models.EmailField() headshot = models.ImageField(upload_to='author_headshots') last_accessed = models.DateTimeField() # urls.py from django.conf.urls import url from books.views import AuthorDetailView urlpatterns = [ #... url(r'^authors/(?P<pk>[0-9]+)/$', AuthorDetailView.as_view(), name='author-detail'), ] # views.py from django.views.generic import DetailView from django.utils import timezone from books.models import Author class AuthorDetailView(DetailView): QuerySet = Author.objects.all () DEF get_object (Self): # call the super class method of the same name Object = Super (AuthorDetailView, Self) .get_object () # record last access date object.last_accessed = timezone.now () object .save () # returns the object return Object # Note: Here, the configuration uses URL grouping called pk, which is to find the default name of the primary key used when DetailView filtered set of queries. # If the group name to a different value, to be set pk_url_kwarg in the view. For details, see DetailView documents.