找不到带有参数“('',)”的“ update_comment”。尝试了1个模式:['comment \\\ /(?P[0-9] +)$']
我正在为新闻网站编码,现在我将使用评论发布功能进行详细说明。
Reverse for 'update_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['comment\\/(?P<news_pk>[0-9]+)$']
我已经尝试了很多方法和时间,但是仍然无法解决,而且我的代码也找不到任何错误,确实需要您的帮助。
评论发布功能位于news_detail.html中。我的项目 新闻中 有两个重要的应用程序, 操作 注释模型正在 运行
这是我的 根urls.py :
path('news', include(('news.urls', 'news'), namespace="news")),
path('', include(('operation.urls', 'operation'), namespace="operation")),
这是 news / urls.py
path('-<int:news_pk>', newsDetailView, name="news_detail")
这是operation / urls.py:
path('comment/<int:news_pk>', views.update_comment, name="update_comment"),
这是 news / view.py
def newsDetailView(request, news_pk):
news = News.objects.get(id=news_pk)
title = news.title
author = news.author_name
add_time = news.add_time
content = news.content
category = news.category
tags = news.tag.annotate(news_count=Count('news'))
all_comments = NewsComments.objects.filter(news=news)
return render(request, "news_detail.html", {
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments,
})
这是 operation / views.py
def update_comment(request, news_pk):
news = News.objects.get(id=news_pk)
comment_form = CommentForm(request.POST or None)
if request.method == 'POST' and comment_form.is_valid():
if not request.user.is_authenticated:
return render(request, 'login.html', {})
comments = comment_form.cleaned_data.get("comment")
news_comment = NewsComments(user=request.user, comments=comments, news=news)
news_comment.save()
return render(request, "news_detail.html", {
'news_comment': news_comment,
'news':news
})
这是news_detail.html:
{% if user.is_authenticated %}
<form method="POST" action="{% url 'operation:update_comment' news.pk %}">{% csrf_token %}
<textarea id="js-pl-textarea" name="comment"></textarea>
<input type="submit" id="js-pl-submit" value="发表评论"></input></form>
-
您没有将
news
对象传递到 news_detail.html 的上下文中。您可以通过传递news
和执行{{ news.title }}
模板中的操作(而不是{{ title }}
)来大大简化视图:def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) return render(request, "news_detail.html", { 'news': news, 'tags': tags, 'all_comments': all_comments, })
现在
news.pk
将作为{% url ... %}
标签的参数。我还确保如果news
找不到对象(在您的代码中,它将崩溃),则会生成404错误。