我用 django 写了一个小型博客网站。我正在使用通用 View 并且一切正常。除了 CreatePostView 之外,它是一个通用的 CreateView:
class CreatePostView(LoginRequiredMixin, generic.CreateView):
model = Post
login_url = '/login/'
redirect_field_name = 'blog_app/post_detail.html'
form_class = PostForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.author = self.request.user
self.object.save()
return super().form_valid(form)
我通过 blog.urls 将其路由到 blog_app.urls
# Project urls
url(r'^blog/', include('blog_app.urls'), name='blog'),
# App urls
url(r'^post/new/$', views.CreatePostView.as_view(), name='post_new'),
但是当我去/blog/post/new/时我会得到
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/post/new/
Raised by: blog_app.views.PostDetailView
但是这会起作用:
url(r'^new/post/$', views.CreatePostView.as_view(), name='post_new'),
现在如果我去
http://127.0.0.1:8000/blog/new/post/
我看到了我的表格。
无论我在斜杠后面写什么,如果第一部分是“post/”,它都会出现 404 错误。至少我相信我已经观察到了这一点。 它也适用于相反的方向:
url(r'^somesuperlongroute/add/$',
views.CreatePostView.as_view(), name='post_new'),
这可行,但它应该是这样的。
在路线的第一部分中使用“post”有什么具体之处?我还有其他 5 条以 'post/' 开头的路由,实际上我可能会在此处包含此文件:
from django.conf.urls import url, include
from . import views
app_name = 'blog_app'
urlpatterns = [
url(r'^$', views.PostListView.as_view(), name='post_list'),
url(r'^about/$', views.AboutView.as_view(), name='about'),
url(r'^post/(?P<slug>[-\w]+)/$',
views.PostDetailView.as_view(), name='post_detail'),
url(r'^post/(?P<slug>[-\w]+)/edit/$',
views.PostUpdateView.as_view(), name='post_edit'),
url(r'^post/new/$',
views.CreatePostView.as_view(), name='post_new'),
url(r'^drafts/$', views.DraftListView.as_view(), name='post_draft_list'),
url(r'^post/(?P<slug>[-\w]+)/remove/$',
views.PostDeleteView.as_view(), name='post_remove'),
url(r'^post/(?P<slug>[-\w]+)/publish/$',
views.post_publish, name='post_publish'),
url(r'^post/(?P<slug>[-\w]+)/comment/$',
views.add_comment_to_post, name='add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$',
views.comment_approve, name='comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$',
views.comment_remove, name='comment_remove'),
]
有什么想法吗?我可以提供您想要的任何模型、 View 、表单,但我发现它们不相关。
最佳答案
Django 将使用第一个匹配的正则表达式,在本例中为 r'^post/(?P<slug>[-\w]+)/$'
。此路由至 PostDetailView
带有 new
的段头。由于您没有包含该 slug 的帖子,因此 View 将引发 404。
要解决此问题,只需输入 CreatePostView
上面PostDetailView
:
urlpatterns = [
...
url(r'^post/new/$',
views.CreatePostView.as_view(), name='post_new'),
url(r'^post/(?P<slug>[-\w]+)/$',
views.PostDetailView.as_view(), name='post_detail'),
...
]
关于python - 如果路由以 'post/' 开头,Django 与 CreateView 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45000677/