python - 根据 Django 中的模型, View /模板中项目的不同显示

标签 python django templates

我有一个模型,看起来像这样:

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/

相关文章:

c++ - 何时使用 `static_assert` 而不是 SFINAE?

python - 数据类行为的变化

python - 使用 SPARQL 进行有限的 RDFS 和 OWL 推理

python - 在Django CreateView中使用当前用户初始化ForeignKey用户

c++ - 具有相同签名的模板不会导致编译器错误

c++ - 完全专用模板中构造函数的外线定义

python - 什么是 DepthwiseConv2D 和 SeparableConv2D?它与keras中的普通Conv2D层有何不同?

python - Django 将参数传递给 CreateView 并用它填充表单

python - Django:非员工用户可以登录管理页面

python - 为什么django不能在数据库之外设置属性?