view 是 Django 的逻辑层 — 一个函数或类,它接收 HTTP request,执行逻辑(查询模型、处理输入),并返回 HTTP response。Views 是你处理当 URL 被访问时发生什么的地方。
Function-based views (FBVs)
python
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse, HttpResponse
def article_list(request):
articles = Article.objects.all() # query models
return render(request, "articles.html", {"articles": articles}) # render a template
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk) # 404 if not found
return render(request, "detail.html", {"article": article})
def api_articles(request):
data = list(Article.objects.values("title", "body"))
return JsonResponse(data, safe=False) # return JSON instead of HTML
基于函数的 view 接收 request(加上任何 URL 参数),完成其工作,并返回响应 — render() 用于 HTML,JsonResponse 用于 JSON,HttpResponse 用于原始输出。
处理不同的 HTTP 方法和输入
python
def create_article(request):
if request.method == "POST":
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return redirect("article_list") # redirect after a successful POST
else:
form = ArticleForm()
return render(request, "create.html", {"form": form})
Views 检查 request.method(GET、POST 等)并通过 request.POST、request.GET、request.user 等访问输入。
Class-based views (CBVs) — 可重用,少样板代码
python
from django.views.generic import ListView, DetailView
# generic CBVs handle common patterns with minimal code
class ArticleListView(ListView):
model = Article # automatically lists all articles
template_name = "articles.html"
class ArticleDetailView(DetailView):
model = Article
Django 还提供 class-based views — 包括通用 views(ListView、DetailView、CreateView),它们用很少的代码实现常见模式(列表、详情、CRUD),减少样板代码。
view 在请求流中的角色
text
Request → URL routing → VIEW (logic) → queries models, renders template → Response
The view is the orchestrator: it connects the URL, the data (models), and the
presentation (template) to produce a response.
为什么这很重要
Views 是 Django 的逻辑层(MVT 中的
