Detailed explanation of django View view layer
Course Objectives
- Understand the concepts and functions of Django views
- Master the use of function view and class view
- Learn to handle HTTP requests and responses
- Understand Django's URL configuration mechanism
View introduction
Django view is a function or class that processes HTTP requests and returns HTTP responses. It is located in the "V" layer (View) of Django MTV architecture and is the core link connecting user input, business logic, and page display.
Core responsibilities of views:
- Receive and parse HTTP requests from the browser
- Call the model layer and service layer to process business logic (such as data addition, deletion, modification and query)
- Generate an HTTP response that meets the requirements and return it to the browser
Function-Based Views
Function view is Django's earliest and most intuitive view form - a Python function corresponds to a URL route, which is suitable for scenarios with simple logic or high customization.
Basic templateless view
Directly returns HTML string or plain text, suitable for debugging or minimalist interface:
from django.http import HttpResponse
import datetime
def current_datetime(request):
# request是django自动传入的HttpRequest对象,包含所有请求信息
now = datetime.datetime.now()
html = f"<html><body>现在是 {now.strftime('%Y-%m-%d %H:%M:%S')}</body></html>"
return HttpResponse(html)
Views combined with templates
usedjango.shortcuts.renderQuickly render HTML templates (the core embodiment of MTV architecture, which separates view logic and page display):
from django.shortcuts import render
# 假设已定义好Article模型
def article_list(request):
articles = Article.objects.filter(is_published=True).order_by("-pub_date")[:10]
# context字典用于向模板传递变量
context = {"articles": articles}
return render(request, "articles/list.html", context)
Handle form POST request
passrequest.methodDifferentiate request types and cooperate withmessagesframe andredirectImplement the complete form process:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
@login_required # 强制登录
def create_article(request):
if request.method == "POST":
# 获取POST表单数据(get的第二个参数是默认值)
title = request.POST.get("title", "").strip()
content = request.POST.get("content", "").strip()
if not title or not content:
messages.error(request, "标题和内容不能为空")
return render(request, "articles/create.html")
# 保存到数据库
Article.objects.create(
title=title,
content=content,
author=request.user,
is_published=True
)
messages.success(request, "文章发布成功!")
# 重定向到列表页(避免表单重复提交)
return redirect("article_list")
# GET请求直接返回空表单
return render(request, "articles/create.html")
Class-Based Views
Class view organizes code in an object-oriented way, and comes with many common scenario encapsulations, which can greatly reduce repeated code and is suitable for standardized scenarios such as CRUD (add, delete, modify) and paging.
Basic View class view
inheritdjango.views.View, by rewriting the function corresponding to the HTTP method name (such asget()、post()) handle the request:
from django.views import View
from django.http import HttpResponse
class HelloView(View):
def get(self, request):
return HttpResponse("Hello, Class-Based Views!")
def post(self, request):
return HttpResponse("Received POST from CBV")
Generic Views
Django has a built-in set of encapsulated general class views, which can be used by directly overriding attributes or lightly overriding methods:
from django.views.generic import ListView, DetailView, CreateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
class ArticleListView(ListView):
model = Article # 指定操作的模型
template_name = "articles/list.html" # 指定渲染的模板
context_object_name = "articles" # 指定传递给模板的变量名(默认是object_list)
paginate_by = 10 # 开启分页,每页10条
# 重写get_queryset自定义查询条件(默认是model.objects.all())
def get_queryset(self):
return Article.objects.filter(is_published=True).order_by("-pub_date")
class ArticleDetailView(DetailView):
model = Article
template_name = "articles/detail.html"
context_object_name = "article"
pk_url_kwarg = "article_id" # 指定URL参数名(默认是pk)
# LoginRequiredMixin放在前面,强制类视图登录
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = Article
fields = ["title", "content", "category"] # 指定表单字段
template_name = "articles/create.html"
success_url = reverse_lazy("article_list") # 成功后跳转的URL(reverse_lazy适合类视图延迟解析)
# 重写form_valid自定义保存逻辑(默认只保存表单字段)
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.is_published = True
return super().form_valid(form)
HTTP request and response processing
Django encapsulates the completeHttpRequest(request) andHttpResponse(Response) system, we only need to operate these two objects.
Common properties of HttpRequest
def handle_request(request):
# 请求方法:GET/POST/PUT/DELETE等
method = request.method
# GET查询参数(如?search=python)
search_keyword = request.GET.get("search", "")
# POST表单数据
username = request.POST.get("username", "")
# 请求头信息(注意HTTP前缀,且转成大写加下划线)
user_agent = request.META.get("HTTP_USER_AGENT", "未知浏览器")
client_ip = request.META.get("REMOTE_ADDR", "")
# 用户与会话信息(需启用Auth和Session中间件)
is_logged_in = request.user.is_authenticated
cart_count = request.session.get("cart_count", 0)
Commonly used HttpResponse subclasses
from django.http import (
HttpResponse,
JsonResponse,
HttpResponseRedirect,
HttpResponseNotFound
)
from django.shortcuts import redirect, get_object_or_404
def response_demo(request):
# 1. 纯文本/HTML响应
text_resp = HttpResponse("这是纯文本响应")
html_resp = HttpResponse("<h1>这是HTML响应</h1>", content_type="text/html")
# 2. JSON响应(自动设置content_type为application/json,且safe=False允许非字典类型)
json_resp = JsonResponse({"status": "success", "data": [1,2,3]}, safe=False)
# 3. 重定向响应(推荐用redirect快捷函数,支持URL名称和对象)
redirect_by_name = redirect("article_list")
redirect_by_obj = redirect(Article.objects.first())
redirect_raw = HttpResponseRedirect("/articles/")
# 4. 404响应(推荐用get_object_or_404快捷函数自动触发)
article = get_object_or_404(Article, id=999)
manual_404 = HttpResponseNotFound("页面走丢了")
URL configuration mechanism
Django maps the URL path to the corresponding view through the URLconf module (usually the urls.py of the project and the urls.py of each application).
Basic URL pattern
# 项目的根urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls), # 管理后台
path("articles/", include("articles.urls")), # 包含应用的子路由
]
# articles应用的子urls.py
from django.urls import path
from . import views
urlpatterns = [
# 函数视图映射
path("", views.article_list, name="article_list"),
path("<int:article_id>/", views.article_detail, name="article_detail"),
# 类视图映射(必须调用.as_view()方法)
path("create/", views.ArticleCreateView.as_view(), name="article_create"),
]
URL parameter type
Django has several commonly used path converters built in:
<int:id>: Matches integers
<slug:slug>: Match slug string (letters, numbers, underscores, hyphens)
<str:title>: Matches except path separators/All strings except
<uuid:uuid>: Match UUID
<path:path>: Matches paths containing separators/All strings of
Decorators and best practices
Commonly used view decorators
Decorators can quickly add additional functions to views, and function views can be used directly@装饰器, for class viewmethod_decoratorOr mixin:
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods, require_POST
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
# 函数视图装饰器
@login_required
@require_POST
def delete_article(request, article_id):
# 处理删除逻辑
pass
@csrf_exempt # 仅用于第三方Webhook等无需CSRF的场景
def wechat_webhook(request):
# 处理微信回调
pass
# 类视图装饰器(用method_decorator)
@method_decorator(login_required, name="dispatch")
class ArticleUpdateView(View):
def get(self, request):
pass
View best practices
- Keep the view simple: Move complex business logic to the model layer or an independent service layer
- Reasonable use of general views: Prioritize the use of general class views in CRUD, paging and other scenarios.
- Handle exceptions correctly: Use
get_object_or_404、get_list_or_404Alternative to manually throwing 404
- Avoid repeated form submission: POST request must be redirected after successful processing (PRG mode)
- Use appropriate status codes: such as 403 (insufficient permissions), 405 (method not allowed), 201 (created successfully)
Course Summary
In this lesson, we systematically studied the core content of the Django view layer:
- Concepts and responsibilities of views
- Basics, templates, and form processing of function views
- Basics of class views, common class views (CRUD, paging, etc.)
- Common operations of HttpRequest and HttpResponse
- URLconf configuration and path converter
- Best practices for commonly used decorators and views
Views are the core entrance to Django applications, and mastering the use of views is crucial to building any web application. In the next lesson we will learn about Django's template layer!