Django - 从视图中为当前用户准备对象
考虑这个模型
class Exercise(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Score(models.Model):
"""Scores of users by exercise"""
exo = models.ForeignKey(Exercise)
user = models.ForeignKey(User)
score = models.IntegerField()
class Meta:
unique_together = (('exo', 'user',),)
,我有一个显示练习
的模板。
<ul>
{% for exo in exos %}
<li>{{ exo }}</li>
{% endfor %}
</ul>
这是视图
def view_exos(request):
"""Lists Exercises"""
objs = {
'exos': Exercise.objects.all(),
}
return render_to_response('content/contents.html', objs
, context_instance=RequestContext(request)
)
现在我想在每个Exercise
(如果有的话)前面显示当前用户的Score
,以便从模板访问它以这种方式:
<li>{{ exo }} - {{ exo.user_score }}</li>
Consider this model
class Exercise(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Score(models.Model):
"""Scores of users by exercise"""
exo = models.ForeignKey(Exercise)
user = models.ForeignKey(User)
score = models.IntegerField()
class Meta:
unique_together = (('exo', 'user',),)
I have a template which displays the Exercise
s.
<ul>
{% for exo in exos %}
<li>{{ exo }}</li>
{% endfor %}
</ul>
Here is the view
def view_exos(request):
"""Lists Exercises"""
objs = {
'exos': Exercise.objects.all(),
}
return render_to_response('content/contents.html', objs
, context_instance=RequestContext(request)
)
Now I'd like to display the Score
of the current user in front of each Exercise
(if there is one) in order to access it from the template in this manner:
<li>{{ exo }} - {{ exo.user_score }}</li>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我要做的就是预先获取所有用户当前的分数,创建一个将练习映射到分数的字典,然后将分数添加为每个练习的属性。类似于:
现在
exos
中的每个练习都有一个current_user_score
属性,它是当前用户该练习的分数(或无)。What I'd do would be to get all the user's current scores up front, create a dictionary mapping exercise to score, then add the score as an attribute of each exercise. Something like:
Now each exercise in
exos
has acurrent_user_score
attribute, which is the current user's score for that exercise (or None).django.contrib.auth
有一个 上下文处理器,将user
变量添加到模板上下文,引用当前用户。这可以让您获取当前用户的所有分数,然后您可以创建一个模板过滤器来返回特定练习的分数。在
templatetags
包内名为exercises.py
的文件中。[将包放入
INSTALLED_APPS
中您的应用之一的文件夹中。请记住templatetags
必须是有效的 Python 包,即。带有__init__.py
]在模板中:
django.contrib.auth
has a context processor that adds auser
variable to the template context, referencing the current user. This can enable you to get all scores for the current user, then you can create a template filter that returns the score for a particular exercise.In a file named
exercises.py
within atemplatetags
package.[Put the package in the folder of one of your apps in
INSTALLED_APPS
. Remembertemplatetags
must be a valid Python package ie. with an__init__.py
]In the template:
也许您可以向您的
Exercise
添加一个属性:Maybe you can add an attribute to your
Exercise
: