当渲染到模板时,如何检查用户与模型的关系 - Django [英] How to check a user's relation to a model when rendering to a template - Django
本文介绍了当渲染到模板时,如何检查用户与模型的关系 - Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,stackoverflow问题的投票功能。
For example, the voting feature for a stackoverflow question.
if user has voted:
highlight arrow
如果模型设置如下:
class Question(models.Model):
#....
voters = models.ManyToManyField(User)
最好做一些像
views.py
class DisplayQuestion:
def __init__(self, question, user):
self.__dict__ = question.__dict__.copy()
self.has_voted = user in question.voters.all()
def show_question(request, question_pk):
question = Question.objects.get(pk=question_pk)
render('question.html', {'question':DisplayQuestion(question, request.user)})
或将其作为另一个变量传递? p>
or pass it as another variable?
def show_question(request, question_pk):
question = Question.objects.get(pk=question_pk)
render('question.html', {'question':question,
'has_voted':user in question.voters.all()})
这似乎不太理想。您可能想要显示一大堆问题,并且不会为每个问题通过 has_voted
。
或是通过ajax()调用检查的最佳方法?
or is the best way to check via an ajax() call?
推荐答案
最简单的方法是在发送到模板之前注释一个属性。
The simplest way is to just annotate an attribute before sending to the template.
question.has_voted = user in question.voters.all()
这篇关于当渲染到模板时,如何检查用户与模型的关系 - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文