Djanog提供了很多适用于各种应用场景的基本视图类, 这些类视图都继承
django.views.generic.base.View
类. 比如
RedirectView
用于重定向,
TemplateView
用于渲染模板.
通用的方法时继承Django提供的各种视图类
from django.views.generic import TemplateView
class AboutView(TemplateView):
template_name = 'about.html'
需要在URLconf中使用as_view()这个类方法将一个基于类的视图转换成函数形式的接口
from django.urls import path
from some_app.views import AboutView
urlpatterns = [
path('about/', AboutView.as_view()),
]
获取书籍列表视图的例子
路由
from django.urls import path
from books.views import BookListView
urlpatterns = [
path('books/', BookListView.as_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, request, *args, **kwargs):
last_book = self.get_queryset().latest('publication_date')
response = HttpResponse()
response['Last_Modified'] = last_book.publication_date.strftime(%a, %d %b %Y %H:%M:%S GMT)
return response