[英]Django user profile only shows logged in user information
我正在嘗試創建一個所有用戶個人資料都是公開的網站。 我稍后使用AbstractUser
對基本用戶模型進行了任何更改。 我在UserProfile
模型中制作了其余的用戶信息。
到目前為止,無論我點擊什么個人資料,我只能看到當前登錄用戶的信息。
這是我第一次使用基於類的視圖,我認為我正在轉向錯誤的方向。
# users/models.py
import uuid # for profile slugs
from django.db import models
from django.conf import settings
from django.db.models.signals import post_save # signal for profile creation
from django.contrib.auth.models import AbstractUser # import base user model for profile
from django.dispatch import receiver
from allauth.account.signals import user_signed_up
class CustomUser(AbstractUser):
pass
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
city = models.CharField(max_length=60, default="")
...
profile_uuid = models.UUIDField(
primary_key=False,
default=uuid.uuid4,
editable=False,
unique=True
) # to use as a "slug" for profiles
def __str__(self):
return self.user.first_name
@receiver(post_save, sender=CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
我正在嘗試使用profile_uuid
作為 URL 的“slug”。 它將顯示為“ https://example.com/profile/ ”。
# urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')), # allauth user management
path('profile/', include('users.urls')), # user profiles
path('', include('pages.urls')), # static pages
]
# users/urls.py
from django.urls import path
from .views import UserProfilePageView
app_name = 'users'
urlpatterns = [
path('<profile_uuid>', UserProfilePageView.as_view(), name='user_profile'), # profile page views
]
視圖函數使用profile_uuid
作為我的 slug,它也在模板中被引用。
# users/views.py
from django.views import generic
from .models import UserProfile
class UserProfilePageView(generic.DetailView):
model = UserProfile
template_name = 'account/profile.html'
slug_field = 'profile_uuid'
slug_url_kwarg = 'profile_uuid'
在創建它時,我收到了一些缺少pk
或slug
字段的錯誤,最終我決定使用 UUID 作為 slug 字段。 主頁上的鏈接(一個列出所有用戶的循環)使用profile_uuid
作為傳遞給users/urls.py
文件的 URL。 我正在嘗試顯示信息,但沒有運氣。
# templates/account/home.html
...
{% for p in profile %}
<a href="{% url 'users:user_profile' p.profile_uuid %}">Profile</a>
{% endfor %}
...
# templates/account/profile.html
{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>{{ user_profile.profile_uuid }}</h1>
<p>{{ user_profile.email }}</p>
{% endblock content %}
以上是拉取配置文件信息的兩次嘗試。 顯然,電子郵件將存儲在CustomUser
模型中; 但是,我試圖確定如何通過 UserProfile 中的 OneToOneField 將其拉出。
此外,應該顯示profile_uuid
(它在 URL 中),但它不會打印到頁面上。 我已經嘗試了對 user_profile、userprofile 等的各種變體,但都沒有成功。
任何關於此事的方向將不勝感激。 最終結果將(希望)是一個個人資料處理程序,它將顯示其他人的個人資料,然后單擊個人資料,它將具有可用的編輯功能。
干杯!
DetailView 將根據文檔將模板中的模型實例公開為object
。
將您的模板更改為:
<h1>{{ object.profile_uuid }}</h1>
<p>{{ object.user.email }}</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.