如何从Django模板中的相关对象获取字段?
问题描述:
我想让每个用户的城市以及他们的评论。 city
字段在UserProfile模型中定义。下面是型号:如何从Django模板中的相关对象获取字段?
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=30, blank=True)
city = models.CharField(max_length=30, choices= CITY_CHOICES)
class Comment(models.Model):
author = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
body = models.TextField()
post = models.ForeignKey(Dastan)
published = models.BooleanField(default=True)
def __unicode__(self):
return unicode("%s: %s" % (self.post, self.body[:60]))
的观点是:
def post(request, post_id=1):
post = Article.objects.get(id = post_id)
comments = Comment.objects.filter(post=post)
d = dict(post=post, comments=comments, form=CommentForm(), user=request.user)
d.update(csrf(request))
return render(request, "article/post.html", d)
而且在模板中,我有:
{% for comment in comments %}
<li> {{commnet.author.userprofile.city}} </li>
<li> <a href="/profile/{{ comment.author }}">{{ comment.author }}</a> </li>
<li><div class="date"> {{ comment.created timesince }}</div>
<div class="comment_body">{{ comment.body | linebreaks }}</div>
{% endfor %}
但不显示的城市。
所以我想知道如何在模板中访问它?
答
问题出在语法上;
commnet
更改它
<li> {{commnet.author.userprofile.city}} </li>
要
<li> {{comment.author.userprofile.city}} </li>
没错。非常愚蠢的错误。我应该在周日停止编码:) – Jand