简体   繁体   English

自定义用户 model 字段 (AbstractUser) 未显示在 django 管理中

[英]Custom User model fields (AbstractUser) not showing in django admin

I have extended User model for django, using AbstractUser method.我使用 AbstractUser 方法将用户 model 扩展为 django。 The problem is, my custom fields do not show in django admin panel.问题是,我的自定义字段没有显示在 django 管理面板中。

My models.py:我的模型.py:

from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    is_bot_flag = models.BooleanField(default=False)

My admin.py:我的管理员.py:

from django.contrib.auth.admin import UserAdmin
from .models import User

admin.site.register(User, UserAdmin)

Thanks谢谢

If all you want to do is add new fields to the standard edit form (not creation), there's a simpler solution than the one presented above.如果您只想将新字段添加到标准编辑表单(而不是创建),那么有一个比上面介绍的更简单的解决方案。

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .models import User


class CustomUserAdmin(UserAdmin):
    fieldsets = (
        *UserAdmin.fieldsets,  # original form fieldsets, expanded
        (                      # new fieldset added on to the bottom
            'Custom Field Heading',  # group heading of your choice; set to None for a blank space instead of a header
            {
                'fields': (
                    'is_bot_flag',
                ),
            },
        ),
    )


admin.site.register(User, CustomUserAdmin)

This takes the base fieldsets, expands them, and adds the new one to the bottom of the form.这将获取基本字段集,展开它们,并将新的字段集添加到表单底部。 You can also use the new CustomUserAdmin class to alter other properties of the model admin, like list_display , list_filter , or filter_horizontal .您还可以使用新的CustomUserAdmin类来更改模型管理员的其他属性,例如list_displaylist_filterfilter_horizontal The same expand-append method applies.相同的 expand-append 方法适用。

You have to override UserAdmin as well, if you want to see your custom fields.如果您想查看自定义字段,您还必须覆盖UserAdmin There is an example here in the documentation.文档中有一个示例here

You have to create the form for creating (and also changing) user data and override UserAdmin .您必须创建用于创建(以及更改)用户数据的表单并覆盖UserAdmin Form for creating user would be:创建用户的表单是:

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = '__all__'

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

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

You override UserAdmin with:您可以使用以下方法覆盖UserAdmin

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

class UserAdmin(BaseUserAdmin):
    add_form = UserCreationForm
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'first_name', 'last_name', 'is_bot_flag', 'password1', 'password2')}
        ),
    )

and then you register:然后你注册:

admin.site.register(User, UserAdmin)

I pretty much copy/pasted this from documentation and deleted some code to make it shorter.我几乎从文档中复制/粘贴了这个并删除了一些代码以使其更短。 Go to the documentation to see the full example, including example code for changing user data.转到文档以查看完整示例,包括更改用户数据的示例代码。

The quickest way to show your extra fields in the Django Admin panel for an AbstractUser model is to unpack the UserAdmin.fieldsets tuple to a list in your admin.py, then edit to insert your field/s in the relevant section and repack as a tuple (see below).在 Django 管理面板中为 AbstractUser 模型显示额外字段的最快方法是将 UserAdmin.fieldsets 元组解压缩到 admin.py 中的列表,然后编辑以在相关部分插入您的字段并重新打包为元组(见下文)。
Add this code in admin.py of your Django app将此代码添加到 Django 应用程序的admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

fields = list(UserAdmin.fieldsets)
fields[0] = (None, {'fields': ('username', 'password', 'is_bot_flag')})
UserAdmin.fieldsets = tuple(fields)

admin.site.register(User, UserAdmin)

Note :注意
list(UserAdmin.fieldsets) gives the following list: list(UserAdmin.fieldsets) 给出以下列表:

[  (None, {'fields': ('username', 'password')}), 
   ('Personal info', {'fields': ('first_name', 'last_name', 'email')}), 
   ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 
'user_permissions')}), 
   ('Important dates', {'fields': ('last_login', 'date_joined')})
]

These fields are by default in Django user models, and here we are modifying the first index of the list to add our custom fields.这些字段默认在 Django 用户模型中,这里我们修改列表的第一个索引以添加我们的自定义字段。

Try this...尝试这个...


models.py模型.py

from django.db import models
from django.contrib.auth.models import AbstractUser


# Create your models here.
class CustomUser(AbstractUser):
    phone_number = models.CharField(max_length=12)

settings.py : Add below line of code in settings.py settings.py :在 settings.py 中添加以下代码行

AUTH_USER_MODEL = 'users.CustomUser'

forms.py forms.py

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


class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = '__all__'

admin.py管理员.py

from django.contrib import admin
from .models import CustomUser
from .forms import CustomUserCreationForm
from django.contrib.auth.admin import UserAdmin


# Register your models here.
class CustomUserAdmin(UserAdmin):
    model = CustomUser
    add_form = CustomUserCreationForm
    fieldsets = (
        *UserAdmin.fieldsets,
        (
            'Other Personal info',
            {
                'fields': (
                    'phone_number',
                )
            }
        )
    )


admin.site.register(CustomUser, CustomUserAdmin)

After all are done then run below command in terminal完成所有操作后,在终端中运行以下命令

python manage.py makemigrations python manage.py makemigrations

python manage.py migrate python 管理.py 迁移

python manage.py runserver python manage.py 运行服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AbstractUser无法使用Django! (替换自定义用户模型) - AbstractUser is not working Django ! (Substituting a custom User model) Django 自定义用户与 AbstractUser - Django custom user with AbstractUser Model 未显示在 Django 管理员使用内置 AbstractUser 创建 - Model Not showing in Django Admin created using built in AbstractUser 如何将图像添加到 Django 自定义用户 Model (AbstractUser)? - How can I add an Image to a Django Custom User Model (AbstractUser)? 在 Django 中更新自定义用户 (AbstractUser) - Updating custom user (AbstractUser) in Django Django 自定义用户创建未在管理站点中显示自定义字段 - Django custom user creation not showing custom fields in admin site Django:自定义用户模型字段未出现在 Django 管理中 - Django: Custom User Model fields not appearing in Django admin 尽管覆盖了默认管理员,但自定义 AbstractUser 的新字段未显示在 Django 管理员中 - New field of custom AbstractUser not showing up in Django admin despite overriding the default admin 将表单字段添加到 django 管理面板中的自定义用户模型 - Addig form fields to a custom user model in django admin panel Django/Wagtail Model API 中未显示管理字段 - Django/Wagtail Model Admin fields not showing in API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM