I want to create pege which previews auhors profile and posts with Django.
I created UserPostListView Class, then I want to search on Profile model by author's name and get profile.
How can I do this?
models.py
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
img = Image.open(self.image.path)
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.image.path)
views.py(UserPostListView Class)
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name = 'posts'
paginate_by = 5
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)
context['profiles'] = Profile.objects.all()
return context
CodePudding user response:
If I understand, you want the author profile of the posts which are in your post queryset that is a single user, so in your get_context_data
you can get author for each post.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["profile"] = Profile.objects.filter(user__username=self.kwargs.get("username"))
return context