gpt4 book ai didi

django-models - Django : error with "username" in my custom user model - 'UserProfile' object has no attribute 'username'

转载 作者:行者123 更新时间:2023-12-01 11:49:28 25 4
gpt4 key购买 nike

我是 Django 新手,在创建自定义用户模型时遇到了一些问题。我遵循了 django 文档中的每个步骤。这是我的模型:

    class UserProfile(models.Model):
user = models.OneToOneField(User)
comment = models.BooleanField()
score = models.IntegerField(null=True)
profilpic = models.ImageField(upload_to="/profilepics")
bio = models.CharField(max_length=140)

然后我用 django-registration 创建了几个用户。但是,当我转到管理员并尝试删除我创建的用户时,或者当我尝试单击用户名时,出现此错误:

AttributeError at /admin/auth/user/3/
'UserProfile' object has no attribute 'username'
Exception Value:
'UserProfile' object has no attribute 'username'
Exception Location: /Users/marc-antoinelacroix/Desktop/Site/sportdub/projet/models.py in __unicode__, line 14

所以我想我必须在我的 UserProfile 模型中创建一个“用户名”,并将它关联到 django 用户的用户名,但我不知道该怎么做...

欢迎任何帮助。

谢谢!

最佳答案

您似乎正在尝试访问

def __unicode__(self):
return self.username

但它必须是

def __unicode__(self):
return self.user

这是一个演示

项目/账户/models.py

class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
homepage = models.URLField(verify_exists=False)
#...

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

项目/账户/admin.py

from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from account.models import UserProfile

admin.site.unregister(User)

class UserProfileInline(admin.StackedInline):
model = UserProfile

class UserProfileAdmin(UserAdmin):
inlines = [UserProfileInline]

admin.site.register(User, UserProfileAdmin)

project/settings.py

AUTH_PROFILE_MODULE = "account.userprofile"

关于django-models - Django : error with "username" in my custom user model - 'UserProfile' object has no attribute 'username' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12836209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com