New to Django and i can't figure out why i keep getting the profile view of the user I logged in with when i try to view other user's profile.
so here if i click on TestUser enter image description here
I get my logged in user profile instead of TestUser's profile enter image description here
notice the url shows http://127.0.0.1:8000/profile/2 which is the TestUser profile's URL but i still get HashemGM's profile.
HTML:
{% extends "Portfolio/base.html" %}
{% block content %}
<body>
<a href=""><i class="bi bi-pencil"></i>Send Message</a>
{% for message in message_list %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ message.sender_user.profile.image.url }}" alt="">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'profile-detail' message.sender_user.id %}">{{message.sender_user.username}}</a><small class="text-muted">  {{message.date_posted}}</small></p> {# |date:"F d, Y" #}
</div>
<p class="article-content mb-4">{{message.content|safe}}</p>
</div>
</article>
<p>{{message.seen}}</p>
{% endfor %}
{% if is_paginated %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a>
{% endif %}
{% endfor %}
{% endif %}
{% endblock content %}
</body>
</html>
HTML
{% extends "Portfolio/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<legend class="border-bottom mb-4 titles-1">Profile Info</legend>
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
</div>
{% endblock content %}
Model:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.utils import timezone
from django.urls import reverse
from ckeditor.fields import RichTextField
from django.contrib.contenttypes.fields import GenericRelation
from Portfolio.models import Contact
# Create your models here.
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 get_absolute_url(self):
return reverse('profile-detail', kwargs={'pk': self.pk})
class Messages(models.Model):
content = RichTextField(blank=True, null=True)
sender_user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, null=True)
receiver_user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, null=True)
date_posted = models.DateTimeField(auto_now_add=True)
seen = models.BooleanField(default=False)
def __str__(self):
return f'{self.content} Messages'
Views:
from django.shortcuts import render, redirect
from django.views.generic import (FormView,TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView, View)
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserChangeForm
from django.contrib import messages
from user.models import Messages, Profile
from django.db.models import Q
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
# Create your views here
''' User Registeration Form '''
class RegisterView(FormView):
form_class = UserRegisterForm
template_name = "user/register.html"
success_url = '/'
def form_valid(self, form):
form.save()
messages.success(self.request, "User is created successfuly")
return super(RegisterView, self).form_valid(form)
''' User Profile '''
class ProfileDetailView(DetailView):
template_name = 'user/profile_detail.html' # <app>/<model>_<viewtype>.html
model = Profile
fields=('image')
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
class ListMessages(LoginRequiredMixin, PermissionRequiredMixin, ListView):
template_name = 'user/messages.html' # <app>/<model>_<viewtype>.html
permission_required = 'message.view_message'
context_object_name = 'message_list'
model = Messages
ordering = ['-date_posted']
paginate_by = 10
def get_queryset(self):
message = self.model.objects.filter(Q(receiver_user=self.request.user))
return message
# def get(self, request, *args, **kwargs):
# messages = Messages.objects.filter(Q(user=request.sender_user) | Q(receiver=request.reciever_user))
# context = {'messages': messages}
# return render(request, 'messages.html', context)
''' Message Creation View'''
class CreateMessage(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
model = Messages
fields = ['reciever_user', 'content']
URLs
from django.urls import path, include
from . import views
from user import views as user_views
urlpatterns = [
path('', views.PostListView.as_view(), name='home'),
path('profile/<int:pk>', user_views.ProfileDetailView.as_view(), name='profile-detail'),
path('user/<str:username>', views.UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'),
path('post/new/', views.PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', views.PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', views.PostDeleteView.as_view(), name='post-delete'),
path('contact/', views.ContactListView.as_view(), name='contact'),
path('contact/new/', views.ContactCreateView.as_view(), name='contact-create'),
]
Here in the profile_detail.html, I just needed to use profile.user.username and profile.user.email instead of user.username and user.email so now it's showing everything correctly. Thanks everyone for the help