当前位置: 首页 > 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…...

日语AI面试高效通关秘籍:专业解读与青柚面试智能助攻

在如今就业市场竞争日益激烈的背景下&#xff0c;越来越多的求职者将目光投向了日本及中日双语岗位。但是&#xff0c;一场日语面试往往让许多人感到步履维艰。你是否也曾因为面试官抛出的“刁钻问题”而心生畏惧&#xff1f;面对生疏的日语交流环境&#xff0c;即便提前恶补了…...

大话软工笔记—需求分析概述

需求分析&#xff0c;就是要对需求调研收集到的资料信息逐个地进行拆分、研究&#xff0c;从大量的不确定“需求”中确定出哪些需求最终要转换为确定的“功能需求”。 需求分析的作用非常重要&#xff0c;后续设计的依据主要来自于需求分析的成果&#xff0c;包括: 项目的目的…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销&#xff0c;平衡网络负载&#xff0c;延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

Appium+python自动化(十六)- ADB命令

简介 Android 调试桥(adb)是多种用途的工具&#xff0c;该工具可以帮助你你管理设备或模拟器 的状态。 adb ( Android Debug Bridge)是一个通用命令行工具&#xff0c;其允许您与模拟器实例或连接的 Android 设备进行通信。它可为各种设备操作提供便利&#xff0c;如安装和调试…...

练习(含atoi的模拟实现,自定义类型等练习)

一、结构体大小的计算及位段 &#xff08;结构体大小计算及位段 详解请看&#xff1a;自定义类型&#xff1a;结构体进阶-CSDN博客&#xff09; 1.在32位系统环境&#xff0c;编译选项为4字节对齐&#xff0c;那么sizeof(A)和sizeof(B)是多少&#xff1f; #pragma pack(4)st…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试

作者&#xff1a;Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位&#xff1a;中南大学地球科学与信息物理学院论文标题&#xff1a;BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接&#xff1a;https://arxiv.…...

Spring Boot+Neo4j知识图谱实战:3步搭建智能关系网络!

一、引言 在数据驱动的背景下&#xff0c;知识图谱凭借其高效的信息组织能力&#xff0c;正逐步成为各行业应用的关键技术。本文聚焦 Spring Boot与Neo4j图数据库的技术结合&#xff0c;探讨知识图谱开发的实现细节&#xff0c;帮助读者掌握该技术栈在实际项目中的落地方法。 …...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

select、poll、epoll 与 Reactor 模式

在高并发网络编程领域&#xff0c;高效处理大量连接和 I/O 事件是系统性能的关键。select、poll、epoll 作为 I/O 多路复用技术的代表&#xff0c;以及基于它们实现的 Reactor 模式&#xff0c;为开发者提供了强大的工具。本文将深入探讨这些技术的底层原理、优缺点。​ 一、I…...

论文笔记——相干体技术在裂缝预测中的应用研究

目录 相关地震知识补充地震数据的认识地震几何属性 相干体算法定义基本原理第一代相干体技术&#xff1a;基于互相关的相干体技术&#xff08;Correlation&#xff09;第二代相干体技术&#xff1a;基于相似的相干体技术&#xff08;Semblance&#xff09;基于多道相似的相干体…...