Issue
In my web App I'm trying to add the function of clicking on the author of a certain post and being able to see their profile and also the posts said user has created. I've managed to get the post list working just fine but when I try to call specific user data, it gives me the data of the logged in user.
Here's how I call the user profile in HTML:
<section class="py-5">
<div class="container my-5">
<div class="row justify-content">
<div class="col-lg-6">
<div class="content-section">
<div class="media">
<img class="rounded-circle profile-img" src="{{ user.profile.image.url }}"/>
<div class="media-body">
<h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works -->
<p class="text-secondary">{{ view.kwargs.username }} {{ user.last_name }}</p>
<p class="text-secondary">{{ user.email }}</p>
<div class="container">
<p class="lead"><Strong>Sobre mi:</strong></p>
<p class="lead">{{ user.description }}</p>
</div>
<br>
<p class="text-secondary">Se unió el {{ user.date_joined }}</p>
<p class="text-secondary">Última vez visto: {{ user.last_login }}</p>
<p class="mb-0">{{ user.profile.about }}</p>
</div>
</div>
</div>
</div>
</div>
Here is my views:
class UserPostListView(ListView):
model = Post
template_name = 'forum/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')
Here is how the problem looks:
As you guys can see, that's Yonas1420's profile, but it's only returning the correct username, because the profile picture, the first and last name, the user bio, the last login, the register day, everything is Winston1420's A.K.A the logged in user.
UPDATES
HTML code for User Post list:
<div class="container my-5">
<div class="row justify-content">
<div class="col-lg-6">
<h2>Publicaciones de <strong><a href="">{{ view.kwargs.username }}</a></strong> ({{ page_obj.paginator.count }}) </h2>
<br>
</div>
</div>
{% for post in posts%}
<article class="media post-content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"j / m / Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.titulo }}</a></h2>
<!-- <p class="article-content">{{ post.contenido }}</p> -->
</div>
</article>
{% endfor %}
My User model template:
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
first_name = models.CharField(_('first name'), max_length=150, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
description = models.CharField(_('About me'), max_length=600, blank=True)
email = models.EmailField(_('email address'), blank=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
Solution
Solved the problem by creating a new view:
class UserProfileView(ListView):
model = Post
template_name = 'forum/user_profile.html'
context_object_name = 'posts'
paginate_by = 1
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')
The logic behind this is that it will retrieve the users posts, so that I can get the specific user's information with commands like {{ post.author.first_name }}
which I can only use when retrieving the user's posts with {% for post in posts %}
, now the key factor into making this work is in the pagination, doesn't matter how many posts this user has, since paginate_by = 1
it's only going to call for a single post regardless of the total amount of posts, and since only one post is being retrieved the for
loop will only run once, resulting in the successful display of all of the user's information only once.
This however does means that we won't be displaying any of the post because it's not practical so have 15 pages of post one for every post, so instead I decided to have the profile focus on the user's information and customization and include an option to access all of said user's profile which takes us to a page with only displays the user's posts.
Answered By - winston1420
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.