gpt4 book ai didi

python - 在此服务器上找不到所请求的 URL。 Django

转载 作者:行者123 更新时间:2023-12-01 04:51:33 25 4
gpt4 key购买 nike

我尝试在页面上写评论,然后在页面上重定向,我在浏览器中有空窗口, [b'<h1>Not Found</h1><p>The requested URL /post/add_comment/test_single_post/ was not found on this server.</p>']AssertionError: 404 != 302 在终端日志中。我不明白为什么在这种情况下找不到页面(404)。

查看

class SinglePost(DetailView):
model = Post
template_name = 'post.html'

def get_context_data(self, **kwargs):
comment_form = CommentForm
context = super(SinglePost, self).get_context_data(**kwargs)
comments = Comments.objects.filter(comment_id=self.object).order_by('-added')
context['comments'] = comments
context['form'] = comment_form
return context


@csrf_protect
def add_comment(request, slug):
"""
Add comment to.
"""
if request.POST:
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.comment = Post.objects.get(slug=slug)
form.save()
return redirect('/post/{0}/'.format(slug))

网址

urlpatterns = patterns('',
url(r'^post/(?P<slug>\S+)/$', SinglePost.as_view(),
name='single_post'),
url(r'^tag/(?P<slug>\S+)/$', TagView.as_view(),
name='tagger'),
url(r'^post/add_comment/(?P<slug>\S+)/$',
'blog.views.add_comment', name="commenter"),
url(r'^$', PostsList.as_view(), name="all_posts"),
)

模板

<h3>Comments:</h3>
{% for comment in comments %}
<p>{{ comment.added }} | {{ comment.author }}</p>
<p>{{ comment.comment_text }}</p>
{% empty %}
<p>There are no comments here yet. Be first :)</p>
{% endfor %}
<form action="/post/add_comment/{{ object.slug }}/" method="POST">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_author">Add your name:</label><br>
{{ form.author|addclass:"form-control" }}
<br/>
<label for="id_comment_text">Add your comment here:</label><br>
{{ form.comment_text|addclass:'form-control comment-textarea' }}
</div>
<br>
<input type="submit" value="Add comment" class="btn btn-primary">
</form>

谁能告诉我如何解决这个问题吗?

最佳答案

您的 single_post 正则表达式捕获所有以“post/”开头的网址。将此 url 放在模式的末尾:

urlpatterns = patterns('',
url(r'^tag/(?P<slug>\S+)/$', TagView.as_view(),
name='tagger'),
url(r'^post/add_comment/(?P<slug>\S+)/$',
'blog.views.add_comment', name="commenter"),
url(r'^$', PostsList.as_view(), name="all_posts"),
url(r'^post/(?P<slug>\S+)/$', SinglePost.as_view(),
name='single_post'),
)

或者,作为更正确的解决方案,将 \S+ 正则表达式更改为有效的 slug 正则表达式 [\w-]+:

urlpatterns = patterns('',
url(r'^post/(?P<slug>[\w-]+)/$', SinglePost.as_view(),
name='single_post'),
url(r'^tag/(?P<slug>[\w-]+)/$', TagView.as_view(),
name='tagger'),
url(r'^post/add_comment/(?P<slug>[\w-]+)/$',
'blog.views.add_comment', name="commenter"),
url(r'^$', PostsList.as_view(), name="all_posts"),
)

关于python - 在此服务器上找不到所请求的 URL。 Django ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com