Django UpdateView视图

UpdateView是Django中的一个通用视图,用于处理对象的更新操作。它允许用户更新一个已经存在的对象。UpdateView通常与一个模型表单一起使用,这样用户就可以看到当前对象的值,并可以修改它们。

1,添加视图

Test/app3/views.py

复制代码
from django.shortcuts import render

# Create your views here.
from .models import Book

from django.views.generic import ListView
class BookListView(ListView):
    model = Book
    context_object_name = 'books'
    template_name = 'books/book_list.html'
    paginate_by = 10 # 设置展示页数数据


from django.views.generic import DetailView
class BookDetailView(DetailView):
    model = Book
    context_object_name = 'book'
    template_name = 'books/book_detail.html'


from django.views.generic.edit import CreateView
class BookCreateView(CreateView):
    model = Book
    template_name = 'books/book_form.html'
    fields = ['title', 'author', 'publication_date']
    success_url = '/app3/books/' # 重定向至书本列表路由地址

from django.urls import reverse_lazy
from django.views.generic.edit import UpdateView
class BookUpdateView(UpdateView):
    model = Book
    fields = ['title', 'author', 'publication_date']
    template_name = 'books/book_edit.html'
    success_url = reverse_lazy('book_list')

2,添加路由地址

Test/app3/urls.py

复制代码
from django.urls import path
from . import views

from .views import BookListView
from .views import BookDetailView
from .views import BookCreateView
from .views import BookUpdateView

urlpatterns = [
    path('books/', BookListView.as_view(), name='book_list'),
    path('books/<int:pk>/', BookDetailView.as_view(), name='book_detail'),
    path('books/new/', BookCreateView.as_view(), name='book_new'),
    path('books/<int:pk>/edit/', BookUpdateView.as_view(), name='BookUpdateView'),

]

3,添加html代码

Test/templates/books/book_edit.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">更新</button>
</form>

</body>
</html>

4,访问页面

Test/templates/books/book_edit.html

http://127.0.0.1:8000/app3/books/1/edit/

相关推荐
追逐时光者1 天前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥1 天前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
你的人类朋友1 天前
什么是API签名?
前端·后端·安全
昵称为空C1 天前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默1 天前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin1 天前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit1 天前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言