当前位置: 首页 > news >正文

每天40分玩转Django:Django视图和URL

Django视图和URL

一、课程概述

学习项目具体内容预计用时
视图基础函数视图、类视图、视图装饰器90分钟
URL配置URL模式、路由系统、命名URL60分钟
请求处理请求对象、响应对象、中间件90分钟

在这里插入图片描述

二、视图基础

2.1 函数视图

# blog/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from .models import Post, Category
from .forms import PostForm# 简单的函数视图
def hello_world(request):return HttpResponse("Hello, Django!")# 带模板渲染的视图
def post_list(request):posts = Post.objects.all().order_by('-publish')return render(request, 'blog/post_list.html', {'posts': posts})# 处理表单的视图
def post_create(request):if request.method == 'POST':form = PostForm(request.POST)if form.is_valid():post = form.save(commit=False)post.author = request.userpost.save()return redirect('blog:post_detail', post.id)else:form = PostForm()return render(request, 'blog/post_form.html', {'form': form})# 详情视图
def post_detail(request, post_id):post = get_object_or_404(Post, id=post_id)return render(request, 'blog/post_detail.html', {'post': post})

2.2 类视图

# blog/views.py
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin# 列表视图
class PostListView(ListView):model = Posttemplate_name = 'blog/post_list.html'context_object_name = 'posts'paginate_by = 10ordering = ['-publish']def get_queryset(self):queryset = super().get_queryset()category_id = self.request.GET.get('category')if category_id:queryset = queryset.filter(category_id=category_id)return queryset# 详情视图
class PostDetailView(DetailView):model = Posttemplate_name = 'blog/post_detail.html'context_object_name = 'post'# 创建视图
class PostCreateView(LoginRequiredMixin, CreateView):model = Posttemplate_name = 'blog/post_form.html'fields = ['title', 'body', 'category', 'status']success_url = reverse_lazy('blog:post_list')def form_valid(self, form):form.instance.author = self.request.userreturn super().form_valid(form)# 更新视图
class PostUpdateView(LoginRequiredMixin, UpdateView):model = Posttemplate_name = 'blog/post_form.html'fields = ['title', 'body', 'category', 'status']def get_success_url(self):return reverse_lazy('blog:post_detail', kwargs={'pk': self.object.pk})# 删除视图
class PostDeleteView(LoginRequiredMixin, DeleteView):model = Postsuccess_url = reverse_lazy('blog:post_list')template_name = 'blog/post_confirm_delete.html'

2.3 视图装饰器

# blog/views.py
from django.contrib.auth.decorators import login_required, permission_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.cache import cache_page# 登录要求装饰器
@login_required
def profile(request):return render(request, 'blog/profile.html', {'user': request.user})# HTTP方法限制装饰器
@require_http_methods(["GET", "POST"])
def post_edit(request, post_id):post = get_object_or_404(Post, id=post_id)if request.method == 'POST':# 处理POST请求passreturn render(request, 'blog/post_edit.html', {'post': post})# 缓存装饰器
@cache_page(60 * 15)  # 缓存15分钟
def category_list(request):categories = Category.objects.all()return render(request, 'blog/category_list.html', {'categories': categories})

三、URL配置

3.1 URL模式

# blog/urls.py
from django.urls import path
from . import viewsapp_name = 'blog'urlpatterns = [# 函数视图URLpath('', views.post_list, name='post_list'),path('post/<int:post_id>/', views.post_detail, name='post_detail'),path('post/new/', views.post_create, name='post_create'),# 类视图URLpath('posts/', views.PostListView.as_view(), name='posts'),path('post/<int:pk>/detail/', views.PostDetailView.as_view(), name='post_detail'),path('post/add/', views.PostCreateView.as_view(), name='post_add'),path('post/<int:pk>/edit/', views.PostUpdateView.as_view(), name='post_edit'),path('post/<int:pk>/delete/', views.PostDeleteView.as_view(), name='post_delete'),# 带参数的URLpath('category/<slug:category_slug>/', views.category_posts, name='category_posts'),path('tag/<slug:tag_slug>/', views.tag_posts, name='tag_posts'),path('archive/<int:year>/<int:month>/', views.archive_posts, name='archive_posts'),
]

3.2 高级URL配置

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import staticurlpatterns = [path('admin/', admin.site.urls),path('blog/', include('blog.urls', namespace='blog')),path('api/', include('blog.api.urls')),  # API URLspath('accounts/', include('django.contrib.auth.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)# 自定义错误页面
handler404 = 'myproject.views.custom_404'
handler500 = 'myproject.views.custom_500'

四、请求和响应处理

4.1 请求对象

# blog/views.py
def process_request(request):# 获取GET参数page = request.GET.get('page', 1)category = request.GET.get('category')# 获取POST数据if request.method == 'POST':title = request.POST.get('title')content = request.POST.get('content')# 获取文件if request.FILES:image = request.FILES['image']# 获取cookiesuser_id = request.COOKIES.get('user_id')# 获取session数据cart = request.session.get('cart', {})# 获取用户信息if request.user.is_authenticated:username = request.user.username

4.2 响应对象

# blog/views.py
from django.http import JsonResponse, FileResponse, StreamingHttpResponse
from django.shortcuts import render, redirectdef multiple_responses(request):# HTML响应return render(request, 'template.html', context)# 重定向return redirect('blog:post_list')# JSON响应data = {'status': 'success', 'message': 'Data received'}return JsonResponse(data)# 文件下载file_path = 'path/to/file.pdf'return FileResponse(open(file_path, 'rb'))# 流式响应def file_iterator(file_path, chunk_size=8192):with open(file_path, 'rb') as f:while True:chunk = f.read(chunk_size)if not chunk:breakyield chunkreturn StreamingHttpResponse(file_iterator(file_path))

4.3 中间件

# blog/middleware.py
import time
from django.utils.deprecation import MiddlewareMixinclass RequestTimingMiddleware(MiddlewareMixin):def process_request(self, request):request.start_time = time.time()def process_response(self, request, response):if hasattr(request, 'start_time'):duration = time.time() - request.start_timeresponse['X-Request-Duration'] = str(duration)return response# settings.py
MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware','blog.middleware.RequestTimingMiddleware',  # 自定义中间件
]

五、实战示例:博客搜索功能

# blog/views.py
from django.db.models import Qdef post_search(request):query = request.GET.get('q', '')results = []if query:results = Post.objects.filter(Q(title__icontains=query) |Q(body__icontains=query) |Q(tags__name__icontains=query)).distinct()return render(request,'blog/search.html',{'query': query,'results': results})# blog/templates/blog/search.html
{% extends "blog/base.html" %}{% block content %}<h2>搜索结果</h2><form method="get"><input type="text" name="q" value="{{ query }}" placeholder="搜索文章..."><button type="submit">搜索</button></form>{% if query %}<h3>包含 "{{ query }}" 的文章:</h3>{% if results %}{% for post in results %}<article><h4><a href="{% url 'blog:post_detail' post.id %}">{{ post.title }}</a></h4><p>{{ post.body|truncatewords:30 }}</p></article>{% endfor %}{% else %}<p>没有找到相关文章。</p>{% endif %}{% endif %}
{% endblock %}

六、常见问题和解决方案

  1. 处理404错误:
# views.py
from django.http import Http404def post_detail(request, post_id):try:post = Post.objects.get(id=post_id)except Post.DoesNotExist:raise Http404("Post does not exist")return render(request, 'blog/post_detail.html', {'post': post})
  1. CSRF验证:
<!-- templates/form.html -->
<form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">提交</button>
</form>
  1. 文件上传处理:
# views.py
def upload_file(request):if request.method == 'POST' and request.FILES['file']:myfile = request.FILES['file']fs = FileSystemStorage()filename = fs.save(myfile.name, myfile)uploaded_file_url = fs.url(filename)return render(request, 'upload.html', {'uploaded_file_url': uploaded_file_url})return render(request, 'upload.html')

七、作业和练习

  1. 实现一个完整的CRUD操作系统
  2. 创建自定义的中间件
  3. 实现文件上传和下载功能
  4. 编写RESTful风格的URL设计
  5. 实现用户认证和授权系统

八、扩展阅读

  1. Django CBV (Class-Based Views) 详解
  2. Django中间件开发最佳实践
  3. RESTful API设计原则
  4. Django安全最佳实践

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

相关文章:

每天40分玩转Django:Django视图和URL

Django视图和URL 一、课程概述 学习项目具体内容预计用时视图基础函数视图、类视图、视图装饰器90分钟URL配置URL模式、路由系统、命名URL60分钟请求处理请求对象、响应对象、中间件90分钟 二、视图基础 2.1 函数视图 # blog/views.py from django.shortcuts import render…...

Kioptirx level4

具体步骤 通过nmap扫描我们所在的网段探测一下存活的主机&#xff0c;发现目标主机开放了80端口可以去访问一下 在访问的同时通过dirb去爆破一下目录&#xff0c;这边发现有一个john的目录不知道是什么可以去 这边在用dirsearch去扫一下防止有漏掉的页面我们没有访问到&#x…...

JPG 转 PDF:免费好用的在线图片转 PDF 工具

JPG 转 PDF&#xff1a;免费好用的在线图片转 PDF 工具 在日常工作和生活中&#xff0c;我们经常需要将图片转换为 PDF 格式。无论是制作电子文档、准备演示材料&#xff0c;还是整理照片集&#xff0c;将图片转换为 PDF 都是一个常见的需求。今天为大家介绍一款完全免费、无需…...

《Django 5 By Example》阅读笔记:p543-p550

《Django 5 By Example》学习第 19 天&#xff0c;p543-p550 总结&#xff0c;总计 8 页。 一、技术总结 1.fixtures (1)定义 A fixture is a collection of files that contain the serialized contents of the database. (2)作用 1)数据导入 一般来说&#xff0c;我们是…...

精品基于Python实现的微信小程序校园导航系统-微信小程序

[含文档PPT源码等] [包运行成功永久免费答疑辅导] 《django微信小程序校园导航系统》该项目采用技术Python的django框架、mysql数据库 &#xff0c;项目含有源码、文档、PPT、配套开发软件、软件安装教程、项目发布教程、核心代码介绍视频等 软件开发环境及开发工具&#xf…...

【数字花园】个人知识库网站搭建:①netlify免费搭建数字花园

目录 [[数字花园]]的构建原理包括三个步骤&#xff1a;五个部署方案教程相关教程使用的平台 步骤信息管理 这里记录的自己搭建数字花园&#xff08;在线个人知识库&#xff09;的经历&#xff0c;首先尝试的是网上普遍使用的方法&#xff0c;也就是本篇文章介绍的。 后面会继续…...

数据仓库工具箱—读书笔记01(数据仓库、商业智能及维度建模初步)

数据仓库、商业智能及维度建模初步 记录一下读《数据仓库工具箱》时的思考&#xff0c;摘录一些书中关于维度建模比较重要的思想与大家分享&#x1f923;&#x1f923;&#x1f923; 博主在这里先把这本书"变薄"~有时间的小伙伴可以亲自再读一读&#xff0c;感受一下…...

分布式 窗口算法 总结

前言 相关系列 《分布式 & 目录》《分布式 & 窗口算法 & 总结》《分布式 & 窗口算法 & 问题》 参考文献 《【算法】令牌桶算法》 固定窗口算法 简介 固定窗口算法是最简单的流量控制算法。固定窗口算法的核心原理是将系统的生命周期划分为一个个…...

docker容器内部启动jupyter notebook但是宿主机无法访问的解决方法

目录 1.问题2.解决方法 1.问题 在docker容器内启动了jupyter notebook&#xff0c;在宿主机内用如下的url无法访问 http://localhost:8888 http://127.0.0.1:8888 启动方法&#xff1a; jupyter notebook 2.解决方法 启动方法加上选项[ --ip‘*’]或者[–ip‘0.0.0.0’] 即启…...

2.2 数据库设计方法

数据库设计流程&#xff1a; 1.需求分析&#xff1a;准确了解分析用户需求&#xff08;包括数据与处理&#xff09;。需求分析是整个设计过程的基础&#xff0c;需求分析决定了构建数据库大厦的速度和质量 2.概念结构设计&#xff1a;概设结构设计是整个数据库设计的关键&…...

ALOHA 协议详解

注&#xff1a;本文为 “ALOHA 协议” 相关文章合辑。 未去重整理。 动态分配信道&#xff08;ALOHA 协议、CSMA 协议&#xff09; QuantumYou 于 2021-07-27 09:32:04 发布 ALOHA 协议 纯 ALOHA 协议 -纯 ALOHA 协议思想&#xff1a;不监听信道&#xff0c;不按时间槽发送…...

Quant connect的优势和不足,学习曲线难

Quant connect的优势和不足 Quant connect作为一个成熟的算法交易平台&#xff0c;具有许多优势&#xff0c;包括&#xff1a; 强大的回测功能&#xff1a;Quant connect提供了丰富的数据源和回测功能&#xff0c;可以对各种交易策略进行全面的回测和分析。 容易上手&#xf…...

分布式 漏桶算法 总结

前言 相关系列 《分布式 & 目录》《分布式 & 漏桶算法 & 总结》《分布式 & 漏桶算法 & 问题》 概述 简介 LBA Leaky Bucket Algorithm 漏桶算法是一种流行于网络通信领域的流量控制/频率限制算法。漏桶算法的核心原理是通过一个概念上的“漏桶”来…...

2450.学习周刊-2024年50周

封面 人生五个球 ✍优秀博文 面对老板安排的工作&#xff0c;事事有回应&#xff0c;有必要吗&#xff1f; 职场精英进阶手册&#xff1a;工作推进五原则&#xff0c;让你合理高效地利用时间 上个班而已&#xff0c;千万别畏手畏脚 理解了雷军说的SU7要守正出奇&#xff0…...

前端性能优化实战:从加载到渲染的全链路提升

"这个页面怎么这么慢啊&#xff1f;" 产品经理小李站在我的工位旁,指着屏幕上的数据大屏抱怨道。我打开 Chrome DevTools 看了一眼,首屏加载时间确实有点吓人 - 足足用了 8 秒。作为一个追求极致体验的前端开发者,这个数字让我坐不住了。 回想起上周的性能检测会议,…...

pdf merge

在 Ubuntu 22.04 上&#xff0c;你可以使用以下命令行工具来合并多个 PDF 文件&#xff1a; 1. pdftk pdftk 是一个强大的 PDF 工具&#xff0c;支持合并、拆分和其他操作。安装和使用方法如下&#xff1a; sudo apt install pdftk pdftk file1.pdf file2.pdf cat output me…...

Python高性能web框架-FastApi教程:(3)路径操作装饰器方法的参数

路径操作装饰器方法的参数 1. 定义带有参数的POST请求路由 app.post(/items,tags[这是items测试接口],summary这是items测试的summary,description这是items测试的description,response_description这是items测试的response_description) def test():return {items: items数据…...

怎么禁用 vscode 中点击 go 包名时自动打开浏览器跳转到 pkg.go.dev

本文引用怎么禁用 vscode 中点击 go 包名时自动打开浏览器跳转到 pkg.go.dev 在 vscode 设置项中配置 gopls 的 ui.navigation.importShortcut 为 Definition 即可。 "gopls": {"ui.navigation.importShortcut": "Definition" }ui.navigation.i…...

bean创建源码

去字节面试&#xff0c;直接让人出门左拐&#xff1a;Bean 生命周期都不知道&#xff01; spring启动创建bean流程 下面就接上了 bean生命周期 doGetBean Object sharedInstance this.getSingleton(beanName); sharedInstance this.getSingleton(beanName, new ObjectF…...

axfbinhexelf文件区别

0 Preface/Foreword axf,bin,hex,elf四个都能存在于嵌入式软件领域。 1 文件介绍 嵌入式软件中常见的文件包含&#xff1a; axf&#xff0c;包含调试信息&#xff0c;文件最大。调试信息放在机器码前面。elfhex&#xff0c;包含地址信息&#xff0c;文件内容较大。bin&#x…...

stm32f4 + Helix + Max98357播放mp3文件

stm32f4的SDIO + FataFs读取SD卡文件在前面的文章中已经实现,下面的配置和修改基于之前的配置实现 配置I2S 模式设置 参数设置 DMA配置 勾选 SPI2 global interrupt 以上都配置完Helix 解码出来的 PCM 数据就发给 MAX98357了 Helix解码库移植...

Motrix Next v3.8.10 | 开源多线程下载管理器神器

Motrix Next v3.8.10是一款全新重构升级的开源多线程下载管理器&#xff0c;老牌原版 Motrix 早已停止更新&#xff0c;老旧架构存在诸多安全漏洞与性能缺陷。而 Motrix Next 基于 Tauri 2Vue3 全新重构开发&#xff0c;补齐了原版技术短板&#xff0c;软件全程纯净无任何广告加…...

AirPodsDesktop:在Windows上解锁苹果耳机的完整体验

AirPodsDesktop&#xff1a;在Windows上解锁苹果耳机的完整体验 【免费下载链接】AirPodsDesktop ☄️ AirPods desktop user experience enhancement program, for Windows and Linux (WIP) 项目地址: https://gitcode.com/gh_mirrors/ai/AirPodsDesktop 你是否曾经在W…...

技术人的英语能力如何影响薪资?数据说话

打开任何一个招聘平台&#xff0c;搜索“软件测试工程师”&#xff0c;你会发现一个越来越普遍的现象。对于那些薪资范围宽、技术描述详尽、公司名号响亮的岗位&#xff0c;末尾往往会附上一句&#xff1a;“英语可作为工作语言”、“英文读写能力优异”、“CET-6以上优先”。这…...

用高效证书管理加固企业数字边界

在当今企业 IT 基础架构的运行中&#xff0c;数字证书已经成为不可或缺的重要组成部分。这在很大程度上源于企业逐渐将 HTTPS 作为默认的数据传输方式&#xff0c;以实现更加安全的通信环境。从安全与隐私角度来看&#xff0c;这无疑是一项积极的改变&#xff0c;因为数据在传输…...

第36天:关系型数据库和MySQL概述

Python学习100天(从入门到精通系列文章) 文章目录 Python学习100天(从入门到精通系列文章) 前言 一、关系型数据库概述 1.1 数据持久化 1.2 数据库发展史 1.3 关系数据库特点 1.4 ER模型(实体关系模型) 1.5 主流关系数据库产品 二、MySQL 简介 三、安装 MySQL 3.1 Window…...

2026毕设求生指南:用产品思维交付你的“第一份作品”

前言&#xff1a;别把毕设当作业&#xff0c;它是你职业起点的“第一份产品” 打开电脑&#xff0c;面对“毕业设计”四个字&#xff0c;你是否感到一片空白&#xff1f; 收藏了无数篇“毕设攻略”&#xff0c;却依然不知道从何下手——看文献像大海捞针&#xff0c;写代码bu…...

大中小型企业数据配置年度成本估算分析

引言 在数字化转型浪潮下&#xff0c;数据已成为企业的核心资产。无论是初创公司、中型企业还是大型集团&#xff0c;合理规划数据存储、处理与分析的成本&#xff0c;对于优化IT预算、提升投资回报率至关重要。本文旨在为不同规模的企业提供一个清晰、可操作的年度数据配置成本…...

Dism++:你的Windows系统优化瑞士军刀,16国语言支持的免费神器

Dism&#xff1a;你的Windows系统优化瑞士军刀&#xff0c;16国语言支持的免费神器 【免费下载链接】Dism-Multi-language Dism Multi-language Support & BUG Report 项目地址: https://gitcode.com/gh_mirrors/di/Dism-Multi-language 你是否曾为Windows系统越来越…...

PddConsumptionModel.java

package pdd;import java.util.ArrayList; import java.util.List; import java.util.Random;/*** 某多多的商业模式&#xff0c;砍价格算法模拟下哈* * * author ZengWenFeng* email 117791303QQ.com* mobile 13805029595* date 2023.11.17*/ public class PddConsumptionMode…...