Reputation: 912
I have a UserPost List View which is a view for a specific user's posts. I am looping the posts of this specific user but I want to add this user's profile details like profile image and other details like email.
So, I am not sure on how to add the user details of the user's post names as designer not the logged-in user.
I can add the user/designer details in every looped post but I don't want it to be repeated with every post I just want it to appear once just like {{ view.kwargs.username }}
as this page is realted only to this user/designer
Here is the models.py
class Post(models.Model):
designer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post")
title = models.CharField(max_length=100, unique=True)
here is the profile model related to every user
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ['username', 'first_name', 'last_name',
'email']
here is the views for the userpostlist which is filtered by a specific user/designer not the logged in user
class UserPostListView(ListView):
model = Post
template_name = "user_posts.html"
context_object_name = 'posts'
queryset = Post.objects.filter(admin_approved=True)
paginate_by = 6
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted')
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
has_items = Item.objects.filter(designer__username=self.kwargs['username']).exists()
context['has_items'] = has_items
return context
here is the template
{% if has_items %}
<h1 class="display-4">Hello, this is {{ view.kwargs.username }} </h1>
<img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear
{{ designer.email }}<----------- I want it to appear
{% else %}
Show nothing
{% endif %}
{% for post in posts %}
Post details
{% endfor %}
Upvotes: 1
Views: 416
Reputation: 476594
You can add this to the context:
from django.contrib.auth import get_user_model
class UserPostListView(ListView):
model = Post
template_name = 'user_posts.html'
context_object_name = 'posts'
queryset = Post.objects.filter(admin_approved=True)
paginate_by = 6
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(
designer__username=self.kwargs['username']
).order_by('-date_posted')
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['designer'] = designer = get_object_or_404(
get_user_model(),
username=self.kwargs['username']
)
context['has_items'] = Item.objects.filter(designer=designer).exists()
return context
Upvotes: 1