Django - 视图层 - 类视图


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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值