视图是可调用的,它接受请求并返回响应。这不仅仅是一个函数,而且Django提供了一些可以用作视图的类的例子。这允许您通过继承和混合来构造视图和重用代码。还有一些用于简单任务的通用视图,我们将在后面介绍,但是您可能希望设计适合您的用例的可重用视图的结构。有关详细信息,请参见基于类的视图引用文档。
基本实例:
Django提供了适合广泛应用的基本视图类。所有视图都继承自View类,该类句柄将视图链接到URL、HTTP方法分派和其他简单特性。RedirectView
用于简单的HTTP重定向,TemplateView
扩展基类以使其也呈现模板。
一、在URLCONF中的简单用法,直接显示html静态页面,不需要调用任何函数:
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^about/$', TemplateView.as_view(template_name="about.html")),
]
二、子类泛型视图:
views.py:
from django.views.generic import TemplateView
class AboutView(TemplateView):
template_name = "about.html"
urls.py:
from django.conf.urls import url
from some_app.views import AboutView
urlpatterns = [
url(r'^about/$', AboutView.as_view()),
]
三、支持HTTP方法:
urls.py:
from django.conf.urls import url
from books.views import BookListView
urlpatterns = [
url(r'^books/$', BookListView.as_view()),
]
views.py:
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