当前位置:   article > 正文

Django UpdateView视图

Django UpdateView视图

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

1,添加视图

Test/app3/views.py

  1. from django.shortcuts import render
  2. # Create your views here.
  3. from .models import Book
  4. from django.views.generic import ListView
  5. class BookListView(ListView):
  6. model = Book
  7. context_object_name = 'books'
  8. template_name = 'books/book_list.html'
  9. paginate_by = 10 # 设置展示页数数据
  10. from django.views.generic import DetailView
  11. class BookDetailView(DetailView):
  12. model = Book
  13. context_object_name = 'book'
  14. template_name = 'books/book_detail.html'
  15. from django.views.generic.edit import CreateView
  16. class BookCreateView(CreateView):
  17. model = Book
  18. template_name = 'books/book_form.html'
  19. fields = ['title', 'author', 'publication_date']
  20. success_url = '/app3/books/' # 重定向至书本列表路由地址
  21. from django.urls import reverse_lazy
  22. from django.views.generic.edit import UpdateView
  23. class BookUpdateView(UpdateView):
  24. model = Book
  25. fields = ['title', 'author', 'publication_date']
  26. template_name = 'books/book_edit.html'
  27. success_url = reverse_lazy('book_list')

2,添加路由地址

Test/app3/urls.py

  1. from django.urls import path
  2. from . import views
  3. from .views import BookListView
  4. from .views import BookDetailView
  5. from .views import BookCreateView
  6. from .views import BookUpdateView
  7. urlpatterns = [
  8. path('books/', BookListView.as_view(), name='book_list'),
  9. path('books/<int:pk>/', BookDetailView.as_view(), name='book_detail'),
  10. path('books/new/', BookCreateView.as_view(), name='book_new'),
  11. path('books/<int:pk>/edit/', BookUpdateView.as_view(), name='BookUpdateView'),
  12. ]

3,添加html代码

Test/templates/books/book_edit.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <form method="POST">
  9. {% csrf_token %}
  10. {{ form.as_p }}
  11. <button type="submit">更新</button>
  12. </form>
  13. </body>
  14. </html>

4,访问页面

Test/templates/books/book_edit.html

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/725106
推荐阅读
相关标签
  

闽ICP备14008679号