Django星级评分无法保存至数据库的问题求助
Django星级评分无法保存问题排查及修复
以下是代码中存在的核心问题及对应修复方案:
1. 模板缺少表单包裹及提交按钮
模板中的单选按钮没有被<form>标签包裹,且无提交按钮,导致点击星星后无法触发POST请求提交数据。
修复后的模板代码片段:
<div> <!-- start rating system --> <div> {% for rating in comment.ratings.all %} {% for i in "12345" %} {% if i|add:"-1" < rating.stars %} <span class="fa fa-star checked"></span> {% else %} <span class="fa fa-star"></span> {% endif %} {% endfor %} {% endfor %} <!-- 添加form标签和提交按钮 --> <form method="POST" action="{% url 'rate_comment' comment.id %}"> {% csrf_token %} <div class="rating" style="text-align:center;" > <input type="radio" id="star5" name="stars" value="5" /> <label for="star5" class="fa fa-star"></label> <input type="radio" id="star4" name="stars" value="4" /> <label for="star4" class="fa fa-star"></label> <input type="radio" id="star3" name="stars" value="3" /> <label for="star3" class="fa fa-star"></label> <input type="radio" id="star2" name="stars" value="2" /> <label for="star2" class="fa fa-star"></label> <input type="radio" id="star1" name="stars" value="1" /> <label for="star1" class="fa fa-star"></label> </div> <button type="submit">提交评分</button> </form> <!-- end rating system --> </div>
2. URL参数与视图参数不匹配
URL配置中参数名为<id>,但视图函数接收的参数是comment_id,导致参数无法正确传递。
修复后的URL配置:
path('<int:comment_id>/', rate_comment, name='rate_comment'),
(添加int:转换器,确保接收整数类型的ID)
3. 视图中redirect使用错误&数据类型不匹配
视图中redirect直接使用模板路径blog/blog-detail.html,Django的redirect应使用URL名称而非模板文件路径;同时request.POST.get('stars')返回字符串,需转为整数匹配模型的IntegerField。
修复后的视图代码片段:
def rate_comment(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) stars = request.POST.get('stars') if stars: # 将stars字符串转为整数 Rating.objects.create(comment=comment, stars=int(stars)) # 替换为你实际的文章详情页URL名称,比如'blog_detail' return redirect('blog_detail', pk=comment.post.pk)
4. 可选优化:处理重复评分场景
当前代码会为同一条评论创建多条评分记录,若要实现“更新已有评分”而非重复创建,可修改视图逻辑:
def rate_comment(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) stars = request.POST.get('stars') if stars: # 查找该评论的已有评分,存在则更新,不存在则创建 rating, created = Rating.objects.get_or_create(comment=comment) rating.stars = int(stars) rating.save() return redirect('blog_detail', pk=comment.post.pk)
5. 潜在问题:验证器未导入
Rating模型中使用了MinValueValidator和MaxValueValidator,需确保已导入:
from django.core.validators import MinValueValidator, MaxValueValidator
内容的提问来源于stack exchange,提问作者Lil Gun
相关产品推荐
相关产品推荐

