Babr
Babr

Reputation: 2081

Django Can not get value of related model data in template

I'd like to show the likers of each post below it.

Here are the models:

class Post(models.Model):
    title = models.CharField(max_length=75, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(User, null=True)
    topic = models.ForeignKey(Topic)
    body = models.TextField(max_length=10000)

    def likers(self):
        return self.postlike_set.all()


class PostLike(models.Model):
    post = models.ForeignKey(Post)
    liker = models.ForeignKey(User, null=True, related_name="post_liker")

And in the template I have:

  {% for post in posts %}

   <div>{{ post.created |timesince }}</div>
   <div>{{ post.creator }}</div>
   <div>{{ post.title }}</div>
   <div>{{ post.body }}</div> 
   <ul>
      {% for liker in post.likers %}
           <li><a href="/path/to/profile/{{ liker.name}}">{{ liker.name}}</a></li> 
      {% endfor %}
   </ul>

   {% endfor %} 

But nothing appears in the template.

How can I fix this?

Upvotes: 0

Views: 44

Answers (1)

Alasdair
Alasdair

Reputation: 309079

Your likers method returns a queryset of PostLike objects. If you want the usernames of the likers, then you need to follow the liker foreign key to the User model.

You also have liker.name which isn't going to work unless your User model has a name field. Use something like liker.username or liker.first_name.

  {% for post_liker in post.likers %}
       <li><a href="/path/to/profile/{{ post_liker.liker.username }}">{{ post_liker.liker.username }}</a></li> 
  {% endfor %}

In this case, it would probably be simpler to use a many-to-many field instead of creating your own joining table.

class Post(models.Model):
    ...
    likers = models.ManyToManyField('User')

Then you don't need the likers method in your model, and your template would simplify to:

  {% for liker in post.likers.all %}
       <li><a href="/path/to/profile/{{ liker.name }}">{{ liker.username }}</a></li> 
  {% endfor %}

Upvotes: 2

Related Questions