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

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…...

iOS 26 携众系统重磅更新,但“苹果智能”仍与国行无缘

美国西海岸的夏天&#xff0c;再次被苹果点燃。一年一度的全球开发者大会 WWDC25 如期而至&#xff0c;这不仅是开发者的盛宴&#xff0c;更是全球数亿苹果用户翘首以盼的科技春晚。今年&#xff0c;苹果依旧为我们带来了全家桶式的系统更新&#xff0c;包括 iOS 26、iPadOS 26…...

DeepSeek 赋能智慧能源:微电网优化调度的智能革新路径

目录 一、智慧能源微电网优化调度概述1.1 智慧能源微电网概念1.2 优化调度的重要性1.3 目前面临的挑战 二、DeepSeek 技术探秘2.1 DeepSeek 技术原理2.2 DeepSeek 独特优势2.3 DeepSeek 在 AI 领域地位 三、DeepSeek 在微电网优化调度中的应用剖析3.1 数据处理与分析3.2 预测与…...

Oracle查询表空间大小

1 查询数据库中所有的表空间以及表空间所占空间的大小 SELECTtablespace_name,sum( bytes ) / 1024 / 1024 FROMdba_data_files GROUP BYtablespace_name; 2 Oracle查询表空间大小及每个表所占空间的大小 SELECTtablespace_name,file_id,file_name,round( bytes / ( 1024 …...

Python:操作 Excel 折叠

💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…...

使用分级同态加密防御梯度泄漏

抽象 联邦学习 &#xff08;FL&#xff09; 支持跨分布式客户端进行协作模型训练&#xff0c;而无需共享原始数据&#xff0c;这使其成为在互联和自动驾驶汽车 &#xff08;CAV&#xff09; 等领域保护隐私的机器学习的一种很有前途的方法。然而&#xff0c;最近的研究表明&…...

Opencv中的addweighted函数

一.addweighted函数作用 addweighted&#xff08;&#xff09;是OpenCV库中用于图像处理的函数&#xff0c;主要功能是将两个输入图像&#xff08;尺寸和类型相同&#xff09;按照指定的权重进行加权叠加&#xff08;图像融合&#xff09;&#xff0c;并添加一个标量值&#x…...

Qt Http Server模块功能及架构

Qt Http Server 是 Qt 6.0 中引入的一个新模块&#xff0c;它提供了一个轻量级的 HTTP 服务器实现&#xff0c;主要用于构建基于 HTTP 的应用程序和服务。 功能介绍&#xff1a; 主要功能 HTTP服务器功能&#xff1a; 支持 HTTP/1.1 协议 简单的请求/响应处理模型 支持 GET…...

《C++ 模板》

目录 函数模板 类模板 非类型模板参数 模板特化 函数模板特化 类模板的特化 模板&#xff0c;就像一个模具&#xff0c;里面可以将不同类型的材料做成一个形状&#xff0c;其分为函数模板和类模板。 函数模板 函数模板可以简化函数重载的代码。格式&#xff1a;templa…...

深入浅出深度学习基础:从感知机到全连接神经网络的核心原理与应用

文章目录 前言一、感知机 (Perceptron)1.1 基础介绍1.1.1 感知机是什么&#xff1f;1.1.2 感知机的工作原理 1.2 感知机的简单应用&#xff1a;基本逻辑门1.2.1 逻辑与 (Logic AND)1.2.2 逻辑或 (Logic OR)1.2.3 逻辑与非 (Logic NAND) 1.3 感知机的实现1.3.1 简单实现 (基于阈…...