1
我想讓每個用戶的城市以及他們的評論。 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 %}
但不顯示的城市。
所以我想知道如何在模板中訪問它?
沒錯。非常愚蠢的錯誤。我應該在週日停止編碼:) – Jand