Django queryset in view isn't returning anything to the html template

208 views Asked by At

I want to show all posts of a specific user in their profile page but only their profile information is being displayed but not the posts.

My initial code was simply trying to loop through the posts in the template like this:

      {% for post in user.posts.all %}
      {% endfor %}

But it didn't work. So I tried this next.

views.py

     user = get_object_or_404(User, username=username)
     post = Post.objects.filter(created_by=user.id)

     context = {
          'user': user,
          'post': post
     }

     return render(request, 'users/profile.html', context)

profile.html

<div class="user-profile">
    <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
    {{ user.username }}
    {{ user.email }}
</div>

<div class="user-post-model">
{% for post in posts %}
   <img class="rounded-circle post-img" src="{{ post.created_by.profile.image.url }}">
   {{ post.title }}
   {{ post.content|safe }}
   {{post.tag}}
   {{ post.created_by }}
   {{ post.created_at|naturaltime}}
{% endfor %}
</div>

It didn't work either

I also tried using a ListView to post the posts. It worked but instead of showing the specific user's profile information it showed the logged in user's profile information but the specific user's posts.

like this:

def profile(request, username):
     user = get_object_or_404(User, username=username)

     context = {
          'user': user
     }

     return render(request, 'users/profile.html', context)

class UserPostListView(ListView):
     model = Post
     template_name = 'users/profile.html'
     context_object_name = 'posts'
     
     def get_queryset(self):
          user = get_object_or_404(User, username=self.kwargs.get('username'))
          return Post.objects.filter(created_by=user).order_by('-created_at')

This is the post model

class Post(models.Model):
     title =  models.CharField(max_length=255)
     content = RichTextField(blank=True, null=True, max_length=30000)
     created_at = models.DateTimeField(default=timezone.now)
     created_by = models.ForeignKey(User, on_delete=models.CASCADE)
     tag =  models.CharField(max_length=255, default='uncategorised')

     class Meta:
          ordering = ('-created_at',)

     def __str__(self):
          return self.title + ' | ' + str(self.created_by)

     def get_absolute_url(self):
          return reverse("post-detail", kwargs={"pk": self.pk})

What is wrong?

1

There are 1 answers

1
NKSM On BEST ANSWER

To loop over the related Post objects to User, use _set (Django Docs).

So in your case user.post_set:

{% for post in user.post_set.all %}
    {{ post.title }}
{% endfor %}