CreateView
是Django提供的一个基于类的视图,用于处理创建新对象的操作。它可以帮助你轻松地创建一个表单页面,用户可以通过这个页面创建新的对象。
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']
Test/app3/urls.py
- from django.urls import path
- from . import views
-
- from .views import BookListView
- from .views import BookDetailView
- from .views import BookCreateView
-
- urlpatterns = [
- path('books/', BookListView.as_view(), name='book_list'),
- path('books/
/' , BookDetailView.as_view(), name='book_detail'), - path('books/new/', BookCreateView.as_view(), name='book_new'),
- ]
-
Test/templates/books/book_form.html
- <!-- 在templates/books/book_form.html中 -->
- <!DOCTYPE html>
- <html>
- <head>
- <title>New book</title>
- </head>
- <body>
- <h1>New book</h1>
- <form method="post">
- {% csrf_token %}
- {{ form.as_p }}
- <button type="submit">Save</button>
- </form>
- </body>
- </html>
http://127.0.0.1:8000/app3/books/new/
这个错误表明Django在尝试重定向到新创建的对象的详情页面时找不到要去的URL。
实际上我们的数据已经成功保存下来了
解决保存后页面访问页面问题可参考:
Django 解决No URL to redirect to.-CSDN博客