我有一个模型,看起来像这样:
class Topic(models.Model):
name = models.CharField(max_length=50)
class Vote(models.Model):
user = models.ForeignKey(User, related_name='user_set')
topic = models.ForeignKey(Topic, related_name='topic_set')
score = models.IntegerField(default=0)
class Meta:
unique_together = ("user", "topic")
在我的索引 View 中,我想显示所有主题的列表。如果用户已经对该主题进行了投票,则应该显示他的分数。如果用户尚未投票,则应显示一个表单供用户投票。
我已使用此方法作为 Topic
类的一部分扩展了模型:
def user_has_already_voted(self, user):
if not Vote.objects.filter(topic=self.id,user=user.id):
return True
else:
return False
但是我不知道这是否是 Django 中的方法,因为我不知道如何使用相应的模板编写 View 来执行此任务。截至目前,我正在使用通用的 IndexView
,如下所示:
class IndexView(generic.ListView):
template_name = 'topics/index.html'
context_object_name = 'latest_topic_list'
def get_queryset(self):
return Topic.objects.order_by('-pub_date')[:5]
最佳答案
使用上下文。在 View 中添加:
def get_context_data(self, **kwargs):
context = {
'is_voted' : self.user_has_already_voted(self.request.user),
}
context.update(kwargs)
return super(IndexView, self).get_context_data(**context)
并在模板中使用:
{% if is_voted %}
Show vote results
{% else %}
Show vote form
{% endif %}
关于python - 根据 Django 中的模型, View /模板中项目的不同显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463882/