Class based view
A view is a callable object that receives a request and then returns a response. This callable object can be more than a function. Django provides some classes that can be used as views. They allow you to structure your view and reuse code using inheritance and mixing. Later, we will introduce some common views for simple tasks, but you may want to design your own reusable view structure to suit your use scenario. For complete details, see the reference documentation for class based views.
Django provides basic view classes, which are suitable for a wide range of applications. All view classes inherit from
ViewClass, which is responsible for connecting views to URLs, HTTP method scheduling, and other simple functions.
RedirectViewFor simple HTTP redirection,
TemplateViewExtend the base class to render the template.
Simple usage in urlconf
The easiest way to use generic views is to create them in urlconf. If you only modify some simple properties of the class based view, you can pass them directly to
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r'^about/', TemplateView.as_view(template_name="about.html")), ]
as_view()The parameter of overrides the property in the class. In this example, we set
template_name。 You can use a similar method to override
Subclassed general view
Second, a more powerful way to use a common view is to inherit an existing view and override its properties in subclasses (for example
template_name）Or method (e.g
get_context_data）To provide a new value or method. For example, consider displaying only one template
about.htmlView of the. Django has a common view
TemplateViewTo do this, so we can simply subclass it and override the name of the template:
# some_app/views.py from django.views.generic import TemplateView class AboutView(TemplateView): template_name = "about.html"
Then we just need to add this new view to our urlconf.
TemplateViewIs a class, not a function, so we point the URL to the class
as_view()Method, which allows the class based view to provide a function like entry:
# urls.py from django.conf.urls import url from some_app.views import AboutView urlpatterns = [ url(r'^about/', AboutView.as_view()), ]
For more information on how to use built-in generic views, refer to the next topic generic class based views.
Support other HTTP methods
Suppose someone wants to access our library through HTTP, which uses views as an API. This API client will connect and download data of newly published books since the last visit at any time. If there are no new books, it will be a waste of CPU and bandwidth to still get books from the database, render a complete response and send it to the client. It would be better to have an API to query the latest release time of books.
We map the URL to the book list view in urlconf:
from django.conf.urls import url from books.views import BookListView urlpatterns = [ url(r'^books/$', BookListView.as_view()), ]
Here is the view:
from django.http import HttpResponse from django.views.generic import ListView from books.models import Book class BookListView(ListView): model = Book def head(self, *args, **kwargs): last_book = self.get_queryset().latest('publication_date') response = HttpResponse('') # RFC 1123 date format response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT') return response
If the view is accessed from a get request, a normal and simple list of objects (using the
book_list.htmlTemplate). But if the client sends a
HEADRequest, the response will have an empty response body instead
Last-ModifiedThe header indicates when the latest book was published. Based on this information, the client can download or not download the complete object list.
In this paperCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.
Django document collaborative translation teamThere is a shortage of staff. Interested friends can join us. It is completely public welfare. Communication group: 467338606.