Django评论功能重定向报错,需实现评论后留原页面
解决评论提交后重定向到文章详情页的问题
问题根源
post_comment重定向报错:错误使用kwargs={'pk': pk}的参数传递方式,Django的redirect函数无需用kwargs包裹关键字参数;且post_comment是处理POST请求的视图,重定向到这里不符合规范,应跳转回GET请求的文章详情页。post-detail重定向失败:该路由需要三个参数——author_slug、文章slug、文章pk,之前未提供完整参数导致路由匹配失败。
具体修复方案
方案1:重定向到文章详情页(推荐)
修改views.py中的post_comment函数,获取文章对象的所有必要参数后跳转:
def post_comment(request, pk): blog = Post.objects.get(pk=pk) comment = Comment( user_comment=request.user, comment=request.POST['comment'], blog=blog ) comment.save() # 生成author_slug:若CustomUser无slug字段,用slugify处理作者名称 from django.utils.text import slugify author_slug = slugify(f"{blog.author.first_name}-{blog.author.last_name}") # 传递post-detail路由所需的全部参数 return redirect('post-detail', author_slug=author_slug, slug=blog.slug, pk=pk)
方案2:修复post_comment重定向的参数错误(不推荐)
若一定要重定向到post_comment视图,修正参数传递方式即可:
def post_comment(request, pk): blog = Post.objects.get(pk=pk) comment = Comment( user_comment=request.user, comment=request.POST['comment'], blog=blog ) comment.save() # 直接传递pk参数,无需kwargs包裹 return redirect('post_comment', pk=pk)
额外优化建议
为CustomUser添加slug字段:
你的post-detail路由依赖author_slug,但当前CustomUser模型无该字段,建议添加并自动生成:# 在CustomUser模型中新增字段 slug = models.SlugField(max_length=255, unique=True, blank=True) # 重写save方法自动生成slug def save(self, *args, **kwargs): if not self.slug: from django.utils.text import slugify self.slug = slugify(f"{self.first_name}-{self.last_name}") super().save(*args, **kwargs)之后重定向时可直接使用
blog.author.slug作为author_slug参数。优化PostDetailView的匹配逻辑:
由于post-detail路由使用pk定位文章,建议明确设置lookup_field避免混淆:class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' lookup_field = 'pk' # 指定用pk查找文章 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['author'] = lowercase_first_name(self.object.author) context['tags'] = self.object.tags.all() context['comments'] = Comment.objects.filter(blog=self.object) return context
内容的提问来源于stack exchange,提问作者Alotab
相关产品推荐
相关产品推荐

