在admin中创建用户时,“自定义用户”模型中的“自定义”字段未显示

时间:2019-05-09 06:51:11

标签: python django django-authentication

我正在使用带有附加字段'uid'的自定义用户模型。当我尝试从管理页面创建新用户时,uid字段未显示。我已经创建了一个自定义用户创建和更新表单。请参见下面的代码。

models.py

from django.db import models

# Create your models here.
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    uid = models.CharField(max_length=50)

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    uid = forms.CharField(label = "uid")

    class Meta(UserCreationForm):
        model = CustomUser
        fields = ('username', 'password', 'uid')

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.uid = self.cleaned_data["uid"]
        if commit:
            user.save()
        return user

我错过了什么还是做错了吗?请帮忙。

编辑: admin.py

from django.contrib import admin
from support.models import CustomUser
# Register your models here.
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['username','password','uid']

admin.site.register(CustomUser, CustomUserAdmin)

1 个答案:

答案 0 :(得分:0)

不知道这是否是正确的方法,如答案https://stackoverflow.com/a/45701173/9740712所示更改CustomUserAdmin,将显示多余的字段。