Django登录后重定向comments页面报错:如何传递id参数?
解决Django的NoReverseMatch错误:给comments路由传id参数
你的问题核心很明确:comments路由要求必须传入一个整数类型的id参数,但登录成功后调用redirect('comments')时没传这个必填参数,导致Django找不到匹配的路由,抛出NoReverseMatch错误。
具体修复步骤:
1. 先修正URL配置里的格式错误
你的URL配置有两处小问题,先调整:
# 原错误配置 path(' comments/int:id/', views. comments, name='comments'), # 修改后:去掉开头空格,用尖括号包裹参数规则 path('comments/<int:id>/', views.comments, name='comments'), path('login/', views.login_user, name='login'),
2. 给redirect传递必填的id参数
登录成功后跳转到评论页,你得明确要跳转到哪个商品的评论页,id的来源一般分两种场景:
场景一:登录时表单携带商品id
比如在登录页面的表单里加个隐藏字段,存储要评论的商品id:<!-- login.html的表单中添加隐藏字段 --> <input type="hidden" name="product_id" value="{{ 目标商品id }}">然后在登录视图里获取这个id,再传给redirect:
def login_user(request): if request.user.is_authenticated: return redirect('/') if request.method=='POST': email=request.POST.get('email') password = request.POST.get('pwd') # 从表单获取商品id product_id = request.POST.get('product_id') user = authenticate(request,email=email,password=password) if user is not None: login(request,user) # 传递id参数给comments路由 return redirect('comments', id=product_id) else: return HttpResponse('账号或密码错误') return render(request,'events/login.html')场景二:跳转到固定id的测试页面
如果只是临时测试,直接传一个数据库中存在的商品id即可:return redirect('comments', id=1) # 这里的1替换成你数据库中实际存在的商品id
3. 额外优化:给评论视图加容错处理
你的comments视图用Product.objects.get(pk=id),如果传入的id不存在会直接报错,建议加异常捕获:
@login_required(login_url="/login") def comments(request,id): try: product = Product.objects.get(pk=id) except Product.DoesNotExist: return HttpResponse('对应的商品不存在') if request.method=='POST': rating=request.POST['rating'] review_title=request.POST['review_title'] review=request.POST['review'] good=request.POST['good'] bad=request.POST['bad'] user=request.user mydata=Post(men=user,product=product, rating=rating,review_title=review_title,review=review,positive_points=good,Negative_points=bad) mydata.save() # 把商品对象传给模板,方便页面展示 return render(request,'events/comments.html', {'product': product})
内容的提问来源于stack exchange,提问作者VINIL ADAMS
相关产品推荐
相关产品推荐

