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

server/2024/12/18 20:19:17/

Django视图和URL

一、课程概述

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

在这里插入图片描述

二、视图基础

2.1 函数视图

python"># 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 类视图

python"># 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 视图装饰器

python"># 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模式

python"># 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配置

python"># 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 请求对象

python"># 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 响应对象

python"># 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 中间件

python"># 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',  # 自定义中间件
]

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

python"># 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错误:
python"># 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. 文件上传处理:
python"># 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大礼包。最后,祝您早日实现财务自由,还请给个赞,谢谢!


http://www.ppmy.cn/server/151263.html

相关文章

vue.js数据绑定和事件处理

单元一 vue.js 数据的绑定 学习目标 &#xff08;1&#xff09;插值 &#xff08;2&#xff09;绑定表达式 任务一 插值 1.1任务描述 数据绑定最常见的形式就是使用 “Mustache” 语法&#xff08;双大括号&#xff09;的文本插值&#xff0c;对于所有的数据绑定&#…

linux网络编程 | c | epoll实现IO多路转接服务器

epoll实现IO多路转接服务器 可通过以下视频学习 06-opell函数实现的多路IO转接_哔哩哔哩_bilibili 通过响应式–多路IO转接实现 文章目录 epoll实现IO多路转接服务器1.思路&功能核心思路 2.代码实现multi_epoll_sever.c运行图 1.思路&功能 **功能&#xff1a;**客…

Android 13 相较于 Android 12 的新特性

标签&#xff1a; Android 13 &#xff1b; Android 13 新特性&#xff1b; Android 13 相较于 Android 12 的新特性及开发者注意事项 一、Android 13 相较于 Android 12 的新特性 Android 13&#xff08;代号 Tiramisu&#xff09;在用户体验、安全性、隐私保护以及开发者工…

Android AOSP 源码中批量替换“phone“为“tablet“的命令详解

我来帮你写一篇关于这条命令的分析博客。 Android 项目中批量替换"phone"为"tablet"的命令详解 前言 在 Android 开发中,有时我们需要批量修改资源文件中的某些文本内容。今天我们来分析一条结合了 grep 和 sed 的强大命令,该命令用于将项目中的 “ph…

【收藏】Cesium 限制相机倾斜角(pitch)滑动范围

1.效果 2.思路 在项目开发的时候&#xff0c;有一个需求是限制相机倾斜角&#xff0c;也就是鼠标中键调整视图俯角时&#xff0c;不能过大&#xff0c;一般 pitch 角度范围在 0 至 -90之间&#xff0c;-90刚好为正俯视。 在网上查阅了很多资料&#xff0c;发现并没有一个合适的…

Edge SCDN深度解析,边缘安全加速的创新实践

边缘安全加速&#xff08;Edge Secure Content Delivery Network&#xff0c;SCDN&#xff09;是酷盾安全推出的边缘集分布式 DDoS 防护、CC 防护、WAF 防护、BOT 行为分析为一体的安全加速解决方案。通过边缘缓存技术&#xff0c;智能调度使用户就近获取所需内容&#xff0c;为…

vite配置tailwindcss

这里以vue3为例&#xff0c;其他的框架只要是vite配置的也可参考这个 项目创建 Vite 需要 Node.js 版本 18 或 20 npm create vitelatest my-vue-app创建完执行命令运行项目 cd my-vue-appnpm installnpm run dev项目正常运行即可 安装和初始化tailwindcss相关插件 安装相…

C#速成(GID+图形编程)

常用类 类说明Brush填充图形形状,画刷GraphicsGDI绘图画面&#xff0c;无法继承Pen定义绘制的对象直线等&#xff08;颜色&#xff0c;粗细&#xff09;Font定义文本格式&#xff08;字体&#xff0c;字号&#xff09; 常用结构 结构说明Color颜色Point在平面中定义点Rectan…