渲染期间的NoReverseMatch

时间:2017-07-31 15:55:52

标签: python django django-views django-testing

我收到此错误:

  

NoReverseMatch at / comments_page / 1 / post_comment /

     

使用参数'('',)找不到'post_comment'的反转。尝试了1种模式:['comments_page /(?P [0-9] +)/ post_comment / $']

我的views.py

def post_comment(request, product_id):
host_product = Product.objects.get(pk=product_id)
comment = Comment()
comment.product = host_product
comment.author = request.POST["author"]
comment.comment_text = request.POST["comment"]
comment.save()
return render(request, 'comments_page/detail.html', {"host_product": host_product})

我的comments_page \ urls.py

from django.conf.urls import url
from . import views

app_name = "comments_page"

urlpatterns = [
    # /comments_page/
    url(r'^$', views.index, name="index"),

    # /comments_page/1/
    url(r'^(?P<product_id>[0-9]+)/$', views.detail, name="detail"),

    # /comments_page/1/post_comment/
    url(r'^(?P<product_id>[0-9]+)/post_comment/$', views.post_comment, name='post_comment'),]

我的detail.html

<form action="{% url 'comments_page:post_comment' product.id %}" method="post">
    {% csrf_token %}
    Name: <input type="text" id="author" name="author">

    Comment:
    <textarea id="comment" name="comment"></textarea><br>
    <input type="submit" value="Post Comment">

我认为我已经将问题确定为产品。在这里

{% url 'comments_page:post_comment' product.id %}

在html页面中。我尝试过几种不同的格式,但我没有运气。请注意,评论正在进行,表单和它的工作原理是更新数据库并加载页面上的条目,但页面没有被重定向。我必须手动重新加载它。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

错误消息显示您传递给{% url %}标记的参数不存在,并解析为空字符串。您的视图确实没有传递product变量,只传递host_product变量。您需要相应地更改标签:

{% url 'comments_page:post_comment' host_product.id %}

答案 1 :(得分:0)

对于那些可能想知道的人,修复方法是将views.py中的return函数更改为此

return render(request, 'comments_page/detail.html', {"product": host_product})

我不明白为什么会这样,但确实如此。有关如何清理我的post_comment函数的任何建议将不胜感激。我觉得使用host_product

过于复杂
相关问题