Reputation: 193
Let's say in a website there is a profile page for users and it is a blog website. So every user has some blogs that they have written. So I want the profile page to be like: It will show the detailed stuffs about that user, like username, email. And also all the blogs they have written should be listed there. Now I have two views here, one for the detailed profile stuffs and another is for listing blogs written by the user.
#view for detailed profile stuffs
class ProfileDetailView(DetailView):
model = User
#view for listing blogs written by user
class UserPostListView(ListView):
model = Post
paginate_by = 5
Also the Post model is like this:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
Now as you can see one view inherits from ListView and another inherits from DetailView. In order to use these two views to render what I am wanting, I can't pass two views to one template. So I need to subclass one of them.Now, as I want to keep pagination, I should subclass UserPostListView and maybe override get_context_data(). So how can I do this? I can't find any satisfactory answer. Also I am very new to django.
Any help will be much appreciated.
Upvotes: 1
Views: 282
Reputation: 193
I was able to do this by subclassing the ListView like this:
class UserPostListView(ListView):
paginate_by = 5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
self.usr = get_object_or_404(User, pk=self.kwargs['pk'])
context['prof'] = self.usr.profile
return context
def get_queryset(self):
return Post.objects.filter(author=self.usr)
Upvotes: 0
Reputation: 354
You need to first update the Post model - add a foreign key field to user in order to know which user has posted what. Next override get_context_data() function in ProfileDetailView and pass all the posts written by the user in the context. Your get_context_data() cal would look something like-
def get_context_data(self, **kwargs):
context = super(ProfileDetailView, self).get_context_data(**kwargs)
user = self.get_object()
posts = Post.objects.filter(user=user)
context.update({'posts': posts})
return context
You can then render the posts for each profile on the template by-
{% for post in posts %}
{{ post.title }}
{{ post.comment }}
{% endfor %}
Upvotes: 2