我正在尝试在默认用户模型中添加一些额外的字段。但是新字段未显示在管理页面中。这是“用户”应用程序的模型。
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
q1 = models.TextField()
q2 = models.TextField()
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreation(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('username', 'email', 'q1', 'q2')
class CustomUserChange(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email', 'q1', 'q2')
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreation, CustomUserChange
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreation
form = CustomUserChange
list_display = ['email', 'username', 'password', 'q1', 'q2']
model = CustomUser
admin.site.register(CustomUser, CustomUserAdmin)
P.S。我在settings.py
中添加了AUTH_USER_MODEL = users.CustomUser
答案 0 :(得分:1)
在您的admin.py文件中,您需要将UserAdmin
替换为:
class CustomUserAdmin(BaseUserAdmin):
form = CustomUserChange
add_form = CustomUserCreation
list_display = ('email', 'username', 'password', 'q1', 'q2')
fields = ('email', 'username', 'password', 'q1', 'q2')
model = CustomUser
admin.site.register(CustomUser, UserAdmin)
请在文档中查看此示例,以进一步了解link
答案 1 :(得分:0)
请在django项目中检查以下内容。
AUTH_USER_MODEL = 'users.models.CustomUser'
添加到settings.py
文件中?确保已将q1
和q2
添加到fields
中的CustomUserAdmin
属性中,如下所示:
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreation
form = CustomUserChange
list_display = ['email', 'username', 'password', 'q1', 'q2']
fields = ['email', 'username', 'password', 'q1', 'q2']
model = CustomUser
答案 2 :(得分:0)
您可以只创建具有OneToOne关系的用户个人资料模型,并在添加用户时使用信号触发它,而无需触摸User模型。
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
class Profile(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
q1 = models.TextField()
q2 = models.TextField()
def __unicode__(self):
return self.user.q1
def create_profile(sender, **kwargs):
user = kwargs["instance"]
if kwargs["created"]:
user_profile = Profile(user=user)
user_profile.save()
post_save.connect(create_profile, sender=User)