Django -自定义模型不能出现在User模型上



我在Django v4中创建了一个模型,我想在User admin视图中显示信息。迁移之后,成功创建了一个新表,并且正在存储数据。下面是代码:

models.py

from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(
User,
on_delete=models.CASCADE
)
address = models.CharField(
max_length=20,
blank=True,
null=True
)
def __str__(self):
return self.user.username

admin.py

from django.contrib import admin
from django.contrib.auth.models import User
from .models import Profile
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'Extra Information'
@admin.register(ProfileInline)
class UserAdmin(admin.ModelAdmin):
inlines = [
ProfileInline,
]

已创建的表存储了以下内容:

user_id

我找到解决办法了。admin.py应该是这样的:

from django.contrib import admin
from django.contrib.auth.models import User
from .models import Profile
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'Extra Information'
class UserAdmin(admin.ModelAdmin):
inlines = [
ProfileInline,
]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

在这种情况下,更好的方法是继承Django的AbstractUser类,添加您的附加字段,然后在settings中设置Django的AUTH_USER_MODEL,以便Django使用您的模型进行身份验证。https://docs.djangoproject.com/en/4.0/ref/settings/std-setting-AUTH_USER_MODEL

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
class Profile(AbstractUser):
address = models.CharField(
max_length=20,
blank=True,
null=True
)
def __str__(self):
return self.username

settings.py

AUTH_USER_MODEL = "<your_app_name>.Profile"

相关内容

  • 没有找到相关文章

最新更新