因此,在我的list_detail.html中,我包含了create_star .html文件,其中放置了我的星级评级表单。
现在我只能对一个用户的帖子评价一次(这是我想要的)。但如果用户已经评分了那么它就会转到else条件(转到create_star。html文件)
但是我想做的是如果一个用户已经评分了。在post_detail.html我想要它显示,例如,如果一个用户评级5,我想在list_detail.html页面的可发布星级评级表单(不可编辑)的地方显示5颗星。但我不知道该怎么做。新手在这里。
在我的模型
class List(models.Model):
title = models.CharField(max_length=120)
genre = models.ManyToManyField('Genre')
creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True)
posted = models.DateTimeField(auto_now_add=True)
content = RichTextField(null=True,default=' ')
type = models.CharField(max_length=10,default="Movie")
spoiler_choices = [(False, 'No'),(True, 'Yes')]
spoiler = models.BooleanField(default=False,null=True, choices = spoiler_choices)
slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True)
def __str__(self):
return f'{self.title}|{self.creator}'
def save(self, *args, **kwargs):
self.slug = slugify(self.title + str(self.posted))
super(List,self).save(*args, **kwargs)
class Starr(models.Model):
user = models.ForeignKey(User,models.CASCADE)
list = models.ForeignKey(List,models.CASCADE)
rate = models.PositiveIntegerField(default=0)
class Meta:
unique_together = ["user", "list"]
def __str__(self):
return self.user.username + " | " + self.list.title + " | " + str(self.rate)
in my views
class TheirDetailView(DetailView):
model = List
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
modell = Review.objects.all()
starr = Starr.objects.all()
context["starr"] = starr
context["modam"] = modell
return context
def create_starr(request):
context = {}
form = StarrForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
context['form'] = form
return render(request, "app/create_starr.html", context)
在我的create_star .html
<div class="starr_cont">
<form class = "starr" method="POST" action="{% url 'app:create_starr' %}" enctype="multipart/form-data">
{% csrf_token %}
<p>
<select name="user" required="" id="id_user">
<option value="{{user.pk}}" selected="">{{user.username}}</option>
</select>
</p>
<p>
<select name="list" required="" id="id_List">
<option value="{{list.pk}}" selected="">{{list.title}}</option>
</select>
</p>
<div class="comment-stars">
<span class="stars-post-comments">
<span class="fa fa-star" id="st1"></span>
<span class="fa fa-star" id="st2"></span>
<span class="fa fa-star" id="st3"></span>
<span class="fa fa-star" id="st4"></span>
<span class="fa fa-star" id="st5"></span>
</span>
</div>
<p>
<input type="number" name="rate" value="0" required="" id="id_rate" placeholder="Rating">
</p>
<div><button type="submit">Rate</button></div>
</form>
</div>
对于用户已经登录的次数,您可以将评分状态保存在数据库中,如果匿名用户可以评分,您可以使用cookie或会话,但这两种方法都不能保证防止用户多次评分