我希望每个用户的城市都有他们的评论。 city
字段在UserProfile模型中定义。以下是模型:
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 %}
但是城市没有显示出来。
所以我想知道如何在模板中访问它?
答案 0 :(得分:1)
问题在于语法;
commnet
改变它
<li> {{commnet.author.userprofile.city}} </li>
到
<li> {{comment.author.userprofile.city}} </li>