0

I'm building a blog using Django, I'm very very new using this tool and I've been trying to figure out how to include the user's profile picture in the users posts view.

Basically in the users posts view, I made a filter ---> www.site.com/user/"username", so you can see all the user posts by date posted. All is working, but I'm not getting the user profile picture.

I really don't know if this is a problem of the query_set or if I'm missing something.

views.py

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post

    class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name='posts'
    paginate_by = 15

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

user_posts.html I'm getting the username but not the user profile.

<div class="col-auto"><img class="img-profile-st" src="{{ post.author.profile.image.url }}"></div>
<h1 class="mb-3" style="text-align: center;">Posted by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>

models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Khris Vandal
  • 147
  • 1
  • 3
  • 14

2 Answers2

0

instead of using this

 src="{{ post.author.profile.image.url }}"

use this

 src="{% static post.author.profile.image.url %}"

since all static files are managed by static urls this will help you out. this is similar question.

Shreyanshu
  • 85
  • 8
0

I resolved this, i wrotte another context to the class in the def get_context_data. So the Views.py:

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name='posts'
    paginate_by = 15

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

    def get_context_data(self, **kwargs):
        context = super(UserPostListView, self).get_context_data(**kwargs)
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        context['postuser'] = Post.objects.filter(author=user).order_by('-date_posted')[:1]
        context['posts'] = Post.objects.filter(author=user).order_by('-date_posted')
        return context
Khris Vandal
  • 147
  • 1
  • 3
  • 14