2015-10-04 133 views
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 %} 

但不顯示的城市。

所以我想知道如何在模板中訪問它?

回答

1

問題出在語法上;

commnet 

更改它

<li> {{commnet.author.userprofile.city}} </li> 

<li> {{comment.author.userprofile.city}} </li> 
+0

沒錯。非常愚蠢的錯誤。我應該在週日停止編碼:) – Jand

相關問題