Django 1.8 official document translation: 3-4-1 class based view

Time:2021-9-18

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.

Basic example

Django provides basic view classes, which are suitable for a wide range of applications. All view classes inherit fromViewClass, 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 toas_view()Method call:

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    url(r'^about/', TemplateView.as_view(template_name="about.html")),
]

Pass toas_view()The parameter of overrides the property in the class. In this example, we setTemplateViewoftemplate_name。 You can use a similar method to overrideRedirectViewofurlProperties.

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 exampletemplate_name)Or method (e.gget_context_data)To provide a new value or method. For example, consider displaying only one templateabout.htmlView of the. Django has a common viewTemplateViewTo 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 classas_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 thebook_list.htmlTemplate). But if the client sends aHEADRequest, the response will have an empty response body insteadLast-ModifiedThe header indicates when the latest book was published. Based on this information, the client can download or not download the complete object list.

translator:Django document collaborative translation team, Original:Overview

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.

Recommended Today

C # regular implementation of UBB parsing class code

The parsed code can pass XHTML   one   Strict verification;It includes title, link, font, alignment, picture, reference, list and other functions  Ubb.ReadMe.htm UBB code description title [H1] title I [/ H1] Title I [H2] Title II [/ H2] Title II [H1] Title III [/ H1] Title III [H4] Title IV [/ H4] Title IV […]