Django类视图
1. 使用基于类的视图
from django.http import HttpResponse
from django.views import view
# 如果使用函数编写一个视图
def my_view(request):
if request.method == 'GET':
return HttpResponse('result')
# 使用基于类的视图:
class MyView(View):
def get(self, request):
return HttpResponse('result')
因为Django的URL解析器期望将请求和关联的参数发送到可调用函数而不是类,所以基于类的视图具有一个 as_view()
类方法,该方法返回一个函数,当请求到达匹配关联模式的URL时,可以调用该函数。该函数创建类的实例,调用 setup()
初始化其属性,然后调用其dispatch()
方法。 dispatch
查看请求以确定它是否为GET
, POST
等等,并将请求中继到匹配方法(如果已定义),如果不是则引发HttpResponseNotAllowed
:
# urls.py
from django.urls import path
from django.views import MyView
urlpatterns = [
path('about/', MyViews.as_view()),
]
2. 对象的通用视图
# models.py
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
website = models.URLField()
class Meta:
ordering = ["-name"]
def __str__(self):
return self.name
class Author(models.Model):
salutation = models.CharField(max_length=10)
name = models.CharField(max_length=200)
headshot = models.ImageField(upload_to='author_headshots')
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField('Author')
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
publication_date = models.DateField()
# views.py
from django.views.generic import ListView
from books.models import Publisher, Book
class PublisherList(ListView):
model = Publisher
queryset = Publish.objects.all() # 使用queryset参数指定对象列表
template_name = 'publisher_list.html' # 使用模版名
context_object_name = 'my_favorite_publishers' # 友好的模版上下文变量名
def get_queryset()
# 动态过滤
pass
def get_context_data(self, **kwargs):
# 通常,get_context_data将所有父类的上下文数据与当前类的上下文数据合并。要在您想要更改上下文的 # 类中保留此行为,您应该确保调用 get_context_data超类。
context = super().get_context_data(**kwargs)
context['book_list'] = Book.objects.all()
return context
# urls.py
from django.urls import path
from books.view import PublisherList
urlpatterns = [
path('publishers/', PublisherList.as_views(), name='publishers'),
]
# 'publisher_list.html'
{% extends "base.html" %}
{% block content %}
<h2>Publishers</h2>
<ul>
{% for publisher in my_favorite_publishers %} # 使用模版上下文变量名
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
{% endblock %}