ListView
、DetailView
、CreateView
、UpdateView
和 DeleteView
是 Django 框架中基于類的通用視圖(Class-Based Generic Views)
?配置 URL 路由
在 urls.py 中為這些視圖配置路由:
from django.urls import path
from .views import (PostListView,PostDetailView,PostCreateView,PostUpdateView,PostDeleteView,
)urlpatterns = [path('', PostListView.as_view(), name='post-list'), # 文章列表頁path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), # 文章詳情頁path('post/new/', PostCreateView.as_view(), name='post-create'), # 創建新文章path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), # 更新文章path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), # 刪除文章
]
1.?ListView
- 用途: 顯示一組對象的列表。
- 典型場景: 展示數據庫中的多條記錄,比如博客文章列表、用戶列表等。
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post# 顯示所有文章的列表
class PostListView(ListView):model = Posttemplate_name = 'blog/post_list.html' # 自定義模板路徑context_object_name = 'posts' # 自定義上下文變量名
<h1>文章列表</h1>
<a href="{% url 'post-create' %}">新建文章</a>
<ul>{% for post in posts %}<li><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a><a href="{% url 'post-update' post.pk %}">編輯</a><a href="{% url 'post-delete' post.pk %}">刪除</a></li>{% endfor %}
</ul>
2.?DetailView
- 用途: 顯示單個對象的詳細信息。
- 典型場景: 查看某篇文章的詳細內容、某個用戶的個人資料等。
# 顯示單篇文章的詳細信息
class PostDetailView(DetailView):model = Posttemplate_name = 'blog/post_detail.html' # 自定義模板路徑context_object_name = 'post' # 自定義上下文變量名
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
<p>發布時間: {{ post.created_at }}</p>
<a href="{% url 'post-list' %}">返回列表</a>
3.?CreateView
- 用途: 創建一個新的對象。
- 典型場景: 提供一個表單讓用戶填寫并提交數據,例如發布一篇新文章。
# 創建新文章
class PostCreateView(CreateView):model = Posttemplate_name = 'blog/post_form.html' # 自定義模板路徑fields = ['title', 'content'] # 表單中需要顯示的字段success_url = reverse_lazy('post-list') # 成功后跳轉到文章列表頁
<h1>{% if object %}編輯文章{% else %}新建文章{% endif %}</h1>
<form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">保存</button>
</form>
<a href="{% url 'post-list' %}">取消</a>
4.?UpdateView
- 用途: 更新一個現有的對象。
- 典型場景: 編輯已有的數據,例如修改一篇文章的內容。
# 更新現有文章
class PostUpdateView(UpdateView):model = Posttemplate_name = 'blog/post_form.html' # 自定義模板路徑fields = ['title', 'content'] # 表單中需要顯示的字段success_url = reverse_lazy('post-list') # 成功后跳轉到文章列表頁
5.?DeleteView
- 用途: 刪除一個現有的對象。
- 典型場景: 刪除某篇文章、某個用戶等。
# 刪除文章
class PostDeleteView(DeleteView):model = Posttemplate_name = 'blog/post_confirm_delete.html' # 自定義模板路徑success_url = reverse_lazy('post-list') # 成功后跳轉到文章列表頁
<h1>確認刪除文章 "{{ object.title }}" 嗎?</h1>
<form method="post">{% csrf_token %}<button type="submit">確認刪除</button>
</form>
<a href="{% url 'post-list' %}">取消</a>