以下是上下文: 我有用户,视频,主题,标准和评级
以下是我的模型:
RATE_CHOICES = zip( range(1,5), range(1,5) )
class VideoCrit(models.Model):
"""Criteria to rate videos on.
Can be multiple for each Topic of Video"""
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Video Criteria'
class VideoTopic(models.Model):
name = models.CharField(max_length=50)
descr = models.TextField(blank=True, null=True)
crits = models.ManyToManyField(VideoCrit,
help_text='Criterias to rate the videos',
blank=True, null=True,
)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Video Topic'
class VideoFile(models.Model):
"""Uploadable by users to be rated and commented"""
name = models.CharField(max_length=50)
descr = models.TextField(blank=True, null=True)
file = models.FileField(upload_to='videos')
topic = models.ForeignKey(VideoTopic)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Chatter Tube'
class VideoRate(models.Model):
"""Users can Rate each Video on the criterias defined for the topic"""
user = models.ForeignKey(User)
video = models.ForeignKey(VideoFile)
crit = models.ForeignKey(VideoCrit)
rate = models.DecimalField(max_digits=2, decimal_places=1, choices=RATE_CHOICES)
class Meta:
unique_together = (('user', 'video', 'crit'),)
verbose_name = 'Tube Rating'
可以吗?
如果是,请从给定VideoFile的模板(基于VideoFile类的DetailView),这是模板的有趣部分
<div id="rating">
<ul>
{% for crit in videofile.topic.crits.all %}
<li>
<div class="rateit"
crit-id="{{ crit.id }}"></div>
{{ crit.name }}
</li>
{% endfor %}
</ul>
</div>
URLconf&amp;图
#urlconf
#...
(r'viewtube/(?P<pk>\d+)$', VideoFileDetailView.as_view()),
#...
#view
class VideoFileDetailView(DetailView):
model = VideoFile
def get_context_data(self, **kwargs):
context = super(VideoFileDetailView, self).get_context_data(**kwargs)
# context['rates'] = VideoRate.objects.filter(video=11)
return context
如何访问当前录制用户对当前视频的评分?
答案 0 :(得分:1)
更新:获取当前登录用户对当前视频的所有评分
# in Views.py
video = VideoFile.objects.get(pk=video_id) #video_id is parameter sent from url
user_ratings = VideoRate.objects.filter(user=request.user).filter(video=video)
# in template
<ul>
{% for rating in user_ratings %}
<li>{{ rating.crit.name }}: {{ rating.rate }}</li>
{% endfor %}
</ul>
PREVIOUSLY:
您应该可以使用以下效果访问登录用户的评级:
user.videorate_set.all
然后,您可以在模板中显示给定用户的所有评级,如下所示:
{% for rating in user.videorate_set.all %}
{{ rating.video }} {{ ratings.rate }}
{% endfor %}
答案 1 :(得分:0)
Django - Generic View Subclassed - url Parameters 给了我答案。我必须将预先过滤的费率添加到模板的上下文中。
class VideoFileDetailView(DetailView):
model = VideoFile
def get_context_data(self, **kwargs):
context = super(VideoFileDetailView, self).get_context_data(**kwargs)
context['rates'] = VideoRate.objects.filter(video=self.object, user=self.request.user)
return context