How to get a field from related object in Django template?

强颜欢笑 提交于 2020-01-30 08:22:09

问题


I want to have each user's city along with their comments. The city field is defined in UserProfile model. Here are the models:

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]))

The view is:

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)

And in template I have:

{% 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 %}

But the city is not displayed.

So I'm wondering how to access it in the template?


回答1:


The problem is in the syntax;

commnet  

Change it

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

To

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


来源:https://stackoverflow.com/questions/32935661/how-to-get-a-field-from-related-object-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!