Django的通用CreateView导致404

时间:2018-02-13 01:03:42

标签: python django

我正在阅读关于Django generic editing views的文档,并尝试用一个简单的例子来关注它们。我有一个项目my_project,其应用my_app具有以下结构:

.
├── __init__.py
├── admin.py
├── apps.py
├── forms.py
├── models.py
├── templates
│   └── my_app
│       ├── author_form.html
│       └── contact.html
├── tests.py
├── urls.py
└── views.py

urls.py

from django.urls import path
from .views import ContactView, AuthorCreate

urlpatterns = [
    path('create/', AuthorCreate.as_view())
]

,项目级urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('my_app/', include('my_app.urls'))
]

views.py

from django.views.generic.edit import FormView, CreateView
from my_app.models import Author


class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

请注意,我没有在示例中实现get_absolute_url方法,因为我不清楚应该如何定义'author-detail'命名的URL。

但问题是输入名称并按下"创建"按钮,我收到404错误:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/my_app/create/None
Using the URLconf defined in my_project.urls, Django tried these URL patterns, in this order:

admin/
my_app/ contact/ [name='contact']
my_app/ create/
The current path, my_app/create/None, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

我怀疑get_absolute_url方法对于CreateView的实现至关重要,但我从文档中不清楚如何实现相应的URL模式。应该是

path('create/<int:pk>/', AuthorCreate.as_view(), name='author-detail')

0 个答案:

没有答案