每天40分玩转Django:Django类视图

embedded/2024/12/29 5:45:03/

Django类视图

一、今日学习内容概述

学习模块重要程度主要内容
类视图基础⭐⭐⭐⭐⭐View类、URLconf配置
通用视图⭐⭐⭐⭐⭐ListView、DetailView等
Mixin机制⭐⭐⭐⭐多重继承、功能组合
自定义类视图⭐⭐⭐⭐视图定制、方法重写

二、类视图基础

2.1 基本类视图

python"># views.py
from django.views import View
from django.http import HttpResponse
from django.shortcuts import renderclass HelloView(View):def get(self, request, *args, **kwargs):return HttpResponse('Hello, World!')class HomeView(View):template_name = 'home.html'def get(self, request):context = {'title': '首页','message': '欢迎访问'}return render(request, self.template_name, context)def post(self, request):# 处理POST请求data = request.POST.get('data')# 处理数据...return HttpResponse('数据已处理')

2.2 URL配置

python"># urls.py
from django.urls import path
from .views import HelloView, HomeViewurlpatterns = [path('hello/', HelloView.as_view(), name='hello'),path('', HomeView.as_view(), name='home'),
]

三、通用类视图实现

3.1 列表视图和详情视图

python"># models.py
from django.db import modelsclass Article(models.Model):title = models.CharField('标题', max_length=200)content = models.TextField('内容')created_at = models.DateTimeField('创建时间', auto_now_add=True)updated_at = models.DateTimeField('更新时间', auto_now=True)author = models.ForeignKey('auth.User', on_delete=models.CASCADE)def __str__(self):return self.title# views.py
from django.views.generic import ListView, DetailView
from .models import Articleclass ArticleListView(ListView):model = Articletemplate_name = 'blog/article_list.html'context_object_name = 'articles'paginate_by = 10def get_queryset(self):queryset = super().get_queryset()return queryset.select_related('author')def get_context_data(self, **kwargs):context = super().get_context_data(**kwargs)context['total_articles'] = self.get_queryset().count()return contextclass ArticleDetailView(DetailView):model = Articletemplate_name = 'blog/article_detail.html'context_object_name = 'article'def get_context_data(self, **kwargs):context = super().get_context_data(**kwargs)# 添加相关文章context['related_articles'] = Article.objects.filter(author=self.object.author).exclude(id=self.object.id)[:5]return context

3.2 创建和编辑视图

python">from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazyclass ArticleCreateView(LoginRequiredMixin, CreateView):model = Articletemplate_name = 'blog/article_form.html'fields = ['title', 'content']success_url = reverse_lazy('article_list')def form_valid(self, form):form.instance.author = self.request.userreturn super().form_valid(form)class ArticleUpdateView(LoginRequiredMixin, UpdateView):model = Articletemplate_name = 'blog/article_form.html'fields = ['title', 'content']def get_queryset(self):# 只允许作者编辑自己的文章return super().get_queryset().filter(author=self.request.user)def get_success_url(self):return reverse_lazy('article_detail', kwargs={'pk': self.object.pk})class ArticleDeleteView(LoginRequiredMixin, DeleteView):model = Articletemplate_name = 'blog/article_confirm_delete.html'success_url = reverse_lazy('article_list')

四、Mixin机制实现

python"># mixins.py
from django.contrib import messages
from django.shortcuts import redirectclass AuthorRequiredMixin:"""确保只有作者可以编辑内容"""def dispatch(self, request, *args, **kwargs):obj = self.get_object()if obj.author != request.user:messages.error(request, '您没有权限执行此操作')return redirect('article_list')return super().dispatch(request, *args, **kwargs)class TitleSearchMixin:"""添加标题搜索功能"""def get_queryset(self):queryset = super().get_queryset()search_query = self.request.GET.get('search')if search_query:queryset = queryset.filter(title__icontains=search_query)return querysetdef get_context_data(self, **kwargs):context = super().get_context_data(**kwargs)context['search_query'] = self.request.GET.get('search', '')return context# 使用Mixin
class ArticleListView(TitleSearchMixin, ListView):model = Articletemplate_name = 'blog/article_list.html'context_object_name = 'articles'paginate_by = 10class ArticleUpdateView(LoginRequiredMixin, AuthorRequiredMixin, UpdateView):model = Articletemplate_name = 'blog/article_form.html'fields = ['title', 'content']

五、类视图流程图

在这里插入图片描述

六、高级类视图示例

6.1 自定义视图组合

python">from django.views.generic import TemplateView
from django.views.generic.dates import (YearArchiveView,MonthArchiveView,DayArchiveView
)class ArticleArchiveView(TemplateView):template_name = 'blog/article_archive.html'def get_context_data(self, **kwargs):context = super().get_context_data(**kwargs)context['years'] = Article.objects.dates('created_at', 'year', order='DESC')return contextclass ArticleYearArchiveView(YearArchiveView):model = Articledate_field = 'created_at'make_object_list = Truetemplate_name = 'blog/article_archive_year.html'class ArticleMonthArchiveView(MonthArchiveView):model = Articledate_field = 'created_at'template_name = 'blog/article_archive_month.html'

6.2 表单处理视图

python">from django.views.generic.edit import FormView
from django import formsclass ContactForm(forms.Form):name = forms.CharField(max_length=100)email = forms.EmailField()message = forms.CharField(widget=forms.Textarea)class ContactView(FormView):template_name = 'contact.html'form_class = ContactFormsuccess_url = '/thanks/'def form_valid(self, form):# 发送邮件name = form.cleaned_data['name']email = form.cleaned_data['email']message = form.cleaned_data['message']# 处理表单数据...messages.success(self.request, '消息已发送')return super().form_valid(form)

七、类视图最佳实践

  1. 视图分组和组织
python"># views/__init__.py
from .article import ArticleListView, ArticleDetailView
from .archive import ArticleArchiveView
from .contact import ContactView# views/article.py
class ArticleViews:"""文章相关视图"""# views/archive.py
class ArchiveViews:"""归档相关视图"""
  1. 通用功能抽象
python">class BaseView(View):"""基础视图类,包含通用功能"""def dispatch(self, request, *args, **kwargs):# 添加通用处理逻辑return super().dispatch(request, *args, **kwargs)class BaseCRUDView(BaseView):"""CRUD操作基础视图"""model = Noneform_class = None
  1. 权限控制
python">from django.contrib.auth.mixins import (LoginRequiredMixin,PermissionRequiredMixin
)class StaffRequiredMixin(LoginRequiredMixin):"""要求用户是员工"""def dispatch(self, request, *args, **kwargs):if not request.user.is_staff:messages.error(request, '需要员工权限')return redirect('home')return super().dispatch(request, *args, **kwargs)

八、测试类视图

python">from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth.models import Userclass ArticleViewTests(TestCase):def setUp(self):self.client = Client()self.user = User.objects.create_user(username='testuser',password='testpass123')def test_article_list_view(self):response = self.client.get(reverse('article_list'))self.assertEqual(response.status_code, 200)self.assertTemplateUsed(response, 'blog/article_list.html')def test_article_create_view(self):# 未登录用户response = self.client.get(reverse('article_create'))self.assertEqual(response.status_code, 302)  # 重定向到登录页# 登录用户self.client.login(username='testuser', password='testpass123')response = self.client.get(reverse('article_create'))self.assertEqual(response.status_code, 200)

通过本章学习,你应该能够:

  1. 理解类视图的工作原理
  2. 使用Django的通用视图
  3. 创建自定义类视图
  4. 使用Mixin机制扩展功能

怎么样今天的内容还满意吗?再次感谢朋友们的观看,关注GZH:凡人的AI工具箱,回复666,送您价值199的AI大礼包。最后,祝您早日实现财务自由,还请给个赞,谢谢!


http://www.ppmy.cn/embedded/149276.html

相关文章

Linux文件目录 --- mkdir命令,创建目录,多级目录,设置目录权限

五、mkdir命令 mkdir 命令用于创建一个或多个目录。它可以创建新的目录结构,有助于文件的组织和管理,下面是该命令的语法以及常用的选项参数。 mkdir [选项] 目录名称 选项作用-m设置新创建目录权限-p循环建立目录-v创建目录时显示详细信息 1.创建单个…

中间件xxl-job安装

拉取镜像 docker pull xuxueli/xxl-job-admin:2.4.2 创建xxl-job-admin容器 docker create --name xxl-job-admin -p 9099:8080 -e PARAMS"--spring.datasource.urljdbc:mysql://192.168.96.57:3306/xxl_job2Unicodetrue&characterEncodingUTF-8 --spring.dataso…

ensp 关于acl的运用和讲解

ACL(Access Control List,访问控制列表)是一种常用于网络设备(如路由器、交换机)上的安全机制,用于控制数据包的流动与访问权限。ACL 可以指定哪些数据包允许进入或离开某个网络接口,基于不同的…

基于DIODES AP43781+PI3USB31531+PI3DPX1207C的USB-C PD Video 之全功能显示器连接端口方案

随着USB-C连接器和PD功能的出现,新一代USB-C PD PC显示器可以用作个人和专业PC工作环境的电源和数据集线器。 虽然USB-C PD显示器是唯一插入墙壁插座的交流电源输入设备,但它可以作为数据UFP(上游接口)连接到连接到TCD&#xff0…

13_HTML5 Audio(音频) --[HTML5 API 学习之旅]

HTML5 引入了 <audio> 标签&#xff0c;使得在网页中嵌入音频文件变得更加简单和直接。使用 <audio> 标签&#xff0c;开发者可以为网站添加音频播放功能而不需要依赖第三方插件&#xff0c;比如 Flash。 以下是 HTML5 <audio> 标签的一些基本用法&#xff…

260-高速AD/DA开发板 大容量FPGA编程 USRP K7-SDR Kintex-7 XC7K325T

硬件规格&#xff1a; 1、 采用Kintex-7 系列&#xff0c;XC7K325T FPGA作为SDR板信号处理的核心&#xff1b; 2、 2片DDR2颗粒&#xff0c;512Mb&#xff1b; 3、 2路高速AD&#xff0c;14bit 250Mbps&#xff1b; 4、 2路高速DA&#xff0c;16bit 1Gbps; 5、 支持外部时钟输入…

Max AI prompt2:

1&#xff0c;prompt1——总体概览 “请根据以下指导原则撰写文献解读&#xff0c;特别关注作者的研究思路和方法论&#xff1a; 1. 研究背景与目的&#xff1a; 概述文章研究的背景&#xff0c;明确研究的主要目的和研究问题。 2. 研究思路&#xff1a; 详细描述作者如何构建…

服务器上加入SFTP------(小白篇 1)

在服务器上配置 SFTP (基于 SSH 的文件传输协议) 通常比传统 FTP 更安全&#xff0c;因为它默认加密通信。以下是详细的配置步骤&#xff0c;以 Ubuntu 或 CentOS 为例。 1.服务器上加入SFTP------(小白篇 1) 2.加入SFTP 用户------(小白篇 2) 3.代码加入SFTP JAVA —&#…