Python 渲染期间的NoReverseMatch
我收到这个错误: NoReverseMatch at/comments\u page/1/post\u comment/ 找不到参数“(“”,)”的“post_comment”的相反项。尝试了1种模式:[“评论页面/(?P[0-9]+)/post\u评论/$”] 我的观点Python 渲染期间的NoReverseMatch,python,django,django-views,django-testing,Python,Django,Django Views,Django Testing,我收到这个错误: NoReverseMatch at/comments\u page/1/post\u comment/ 找不到参数“(“”,)”的“post_comment”的相反项。尝试了1种模式:[“评论页面/(?P[0-9]+)/post\u评论/$”] 我的观点 def post_comment(request, product_id): host_product = Product.objects.get(pk=product_id) comment = Comment() comm
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})
我的评论\u页面\url.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'),]
在html页面中。我尝试过用几种不同的方式格式化它,但我没有任何运气。请注意,注释正在进行,表单和它的工作方式是更新数据库和在页面上加载条目,但是页面没有被重定向。我必须手动重新加载它。任何帮助都将不胜感激。错误消息显示传递给
{%url%}
标记的参数不存在,并解析为空字符串。您的视图实际上没有传入产品
变量,只有主机产品
变量。您需要相应地更改标记:
{% url 'comments_page:post_comment' host_product.id %}
对于那些可能想知道的人来说,解决方法是将views.py中的返回函数更改为
return render(request, 'comments_page/detail.html', {"product": host_product})
我不明白这为什么有效,但它确实有效。任何关于如何清理我的post_评论功能的建议都将不胜感激。我觉得使用host_product(主机产品)试试
{%url'评论页面:post_comment'product_id=host_product.id%}
!这会将用户重定向到没有拉入任何数据库信息的页面,类似于knbk的建议。我尝试了你的建议,它会停止错误,但它会将用户重定向到没有拉入任何数据库信息的通用页面。通过将上下文更改为{“product”:host_product},我自己找到了一个解决方案。我不知道为什么会这样。我觉得在host_产品中保存对象的id可能会使事情变得过于复杂。在这个过程中的某个地方,我对传递id的位置或标识对象的位置失去了理解。@brno32没关系,你可以称它为product
或host\u product
,这无关紧要。唯一重要的是你要始终如一地使用你选择的名字。显然,您在别处使用了名称产品
。
{% url 'comments_page:post_comment' host_product.id %}
return render(request, 'comments_page/detail.html', {"product": host_product})