Django学习笔记四 (类视图)

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查看请求以确定它是否为GETPOST等等,并将请求中继到匹配方法(如果已定义),如果不是则引发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 %}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值