Django 在查看其他用户配置文件时,我得到了登录用户的配置文件



刚进入Django,我不明白为什么当我试图查看其他用户的配置文件时,我总是获得登录用户的配置文件视图。

如果我点击TestUser输入图片描述

我得到我登录的用户配置文件,而不是TestUser的配置文件输入图片描述

注意url显示http://127.0.0.1:8000/profile/2,这是TestUser配置文件的url,但我仍然得到HashemGM的配置文件。

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">&emsp; {{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 %}

模型:

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' 

视图:

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']
url

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'),
]

在profile_detail.html中,我只需要使用profile.user.username和profile.user.email而不是user。用户名和用户名。电子邮件,现在一切都显示正确。谢谢大家的帮助

<div class="media-body">
<h2 class="account-heading">{{ profile.user.username }}</h2>
<p class="text-secondary">{{ profile.user.email }}</p>
</div>
</div>

最新更新