【发布时间】:2021-07-05 12:15:55
【问题描述】:
我想在 Django 中显示平均 5 星评级。如下图所示。
在上图中,所有用户对特定产品的平均评分加上评论计数。
因此,为了将评分存储到 DB,我使用了类似这样的代码。
views.py
def product_detail(request, id):
product_detail = Product.objects.get(id=id)
review = Review.objects.filter(product = product_detail)
return render(request, 'detailpage/productdetail.html',
{'product_detail':product_detail, 'review':review})
review.html
<div class="container col-sm-7">
<form action="/product_review">
<input type="hidden" name="product_id" id="product_id" value="{{product.id}}">
<h4 style="font-weight:bold" class="mt-5">Create Review</h4>
<hr>
<h5 style="font-weight:bold">Overall Rating</h5>
<div class="stars">
<input class="star star-5" id="star-5" type="radio" name="rate" value="5" /> <label class="star star-5" for="star-5"></label> <input class="star star-4" id="star-4" type="radio" name="rate" value="4"/> <label class="star star-4" for="star-4"></label> <input class="star star-3" id="star-3" type="radio" name="rate" value="3"/> <label class="star star-3" for="star-3"></label> <input class="star star-2" id="star-2" type="radio" name="rate" value="2"/> <label class="star star-2" for="star-2"></label> <input class="star star-1" id="star-1" type="radio" name="rate" value="1rate"/> <label class="star star-1" for="star-1"></label>
</div>
<h5 style="font-weight:bold">Add a headline</h5>
<input type="text" name="subject" class="form-control" id="inputDefault" autocomplete="off">
<br>
<h5 style="font-weight:bold">Add a written review</h5>
<textarea class="form-control" name="comment" id="exampleTextarea" rows="3"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
models.py
class Review(models.Model):
user = models.ForeignKey(User, models.CASCADE)
product = models.ForeignKey(Product, models.CASCADE,null=True, blank=True)
subject = models.CharField(max_length = 100, null=True, blank=True)
comment = models.TextField(max_length=250, null=True, blank=True)
rate = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
现在
我想在这段代码中显示平均评论
<div class="review-feedback">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
</div>
【问题讨论】:
标签: python django django-models django-views django-forms