最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Django后台管理页面中给新增用户添加自定义字段

Django crifan 4744浏览 0评论

折腾:

【已解决】给Django系统中添加一个新的用户

期间,对于:

【已解决】Django添加用户出错:django.db.utils.IntegrityError 1062 Duplicate entry for key mobile_phone_number

还是希望通过在新增用户的界面中,额外加上针对此处的新用户的自定义的字段,以便于方便通过界面去新增用户。

django admin page create user add more field

For the django admin, how do I add a field to the User model and have it editable in the admin? – Stack Overflow

内容太老是2009年的。。。

User authentication in Django | Django documentation | Django

-》提示文档是dev最新版本,所以选择符合此处2.0.6的2.0版本:

User authentication in Django | Django documentation | Django

Using the Django authentication system | Django documentation | Django

How to add a field to the Django Admin Add User form using UserCreationForm. Add this to a admin.py and alter to whatever fields you’d like

8年前的代码。。。

Django: adding new field to the admin user in Django – Stack Overflow

Customizing authentication in Django | Django documentation | Django

https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#extending-django-s-default-user

https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#specifying-custom-user-model

https://docs.djangoproject.com/en/2.0/topics/db/models/#abstract-base-classes

此处目前已有代码是:

apps/user/admin.py

from django.contrib import admin

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

from .models import User, FunctionGroup

# Register your models here.

class UserAdmin(AuthUserAdmin):

    list_display = (‘id’, ‘mobile_phone_number’, ’email’, ‘username’, ‘name’,

                    ‘is_superuser’, ‘is_active’)

    list_filter = (‘is_superuser’, ‘is_active’)

    search_fields = (‘mobile_phone_number’, ’email’, ‘username’, ‘name’)

    fieldsets = AuthUserAdmin.fieldsets + ((None, {

        ‘fields’: (‘mobile_phone_number’, ‘name’)

    }), )

class FunctionGroupAdmin(admin.ModelAdmin):

    list_display = (‘id’, ‘owner’, ‘name’, ‘description’, ‘created_at’,

                    ‘updated_at’)

    search_fields = (‘owner__username’, ‘name’, ‘description’)

admin.site.register(User, UserAdmin)

admin.site.register(FunctionGroup, FunctionGroupAdmin)

加上了add_fieldsets后:

class UserAdmin(AuthUserAdmin):

    list_display = (‘id’, ‘mobile_phone_number’, ’email’, ‘username’, ‘name’,

                    ‘is_superuser’, ‘is_active’)

    list_filter = (‘is_superuser’, ‘is_active’)

    search_fields = (‘mobile_phone_number’, ’email’, ‘username’, ‘name’)

    fieldsets = AuthUserAdmin.fieldsets + ((None, {

        ‘fields’: (‘mobile_phone_number’, ‘name’)

    }), )

    add_fieldsets = (

        (

            None,

            {

                ‘classes’: (‘wide’,),

                ‘fields’: (‘name’, ‘username’, ‘mobile_phone_number’, ’email’, ‘password1’, ‘password2’)

            }

            # here are fields you want to have in django-admin AddUser view

            # one of the most important place above

        ),

    )

界面上是看到了:

但是想要显示不同字段的自己的文字

https://gist.github.com/riklomas/511440

有个:

self.fields[’email’] = forms.EmailField(label=_("E-mail"), max_length=75)

去参考看看

然后扩展了UserCreationForm后:

from django.contrib import admin

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

from .models import User, FunctionGroup

from django.contrib.auth.forms import UserCreationForm

from django import forms

from django.utils.translation import ugettext_lazy as _

# Register your models here.

class UserAdmin(AuthUserAdmin):

    list_display = (‘id’, ‘mobile_phone_number’, ’email’, ‘username’, ‘name’,

                    ‘is_superuser’, ‘is_active’)

    list_filter = (‘is_superuser’, ‘is_active’)

    search_fields = (‘mobile_phone_number’, ’email’, ‘username’, ‘name’)

    fieldsets = AuthUserAdmin.fieldsets + ((None, {

        ‘fields’: (‘mobile_phone_number’, ‘name’)

    }), )

    add_fieldsets = (

        (

            None,

            {

                ‘classes’: (‘wide’,),

                ‘fields’: (‘name’, ‘username’, ‘mobile_phone_number’, ’email’, ‘password1’, ‘password2’)

            }

            # here are fields you want to have in django-admin AddUser view

            # one of the most important place above

        ),

    )

class FunctionGroupAdmin(admin.ModelAdmin):

    list_display = (‘id’, ‘owner’, ‘name’, ‘description’, ‘created_at’,

                    ‘updated_at’)

    search_fields = (‘owner__username’, ‘name’, ‘description’)

class UserCreationFormExtended(UserCreationForm):

    def __init__(self, *args, **kwargs):

        super(UserCreationFormExtended, self).__init__(*args, **kwargs)

        self.fields[‘name’] = forms.CharField(label=_("昵称"), max_length=128)

        self.fields[‘mobile_phone_number’] = forms.CharField(label=_("手机号"), max_length=11)

        self.fields[’email’] = forms.EmailField(label=_("邮箱"), max_length=50)

UserAdmin.add_form = UserCreationFormExtended

admin.site.register(User, UserAdmin)

admin.site.register(FunctionGroup, FunctionGroupAdmin)

其中部分字段的max_length参考了定义:

apps/user/models.py

class User(AbstractUser):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    is_active = models.BooleanField(default=False)

    name = models.CharField(blank=True, max_length=128)

    mobile_phone_number = models.CharField(blank=False, null=False,

                                           max_length=11, unique=True)

其中以为models中的CharField和forms.CharField字段通用呢,所以传入了:

blank=False

等参数:

self.fields[‘mobile_phone_number’] = forms.CharField(label=_("手机号"), blank=False, max_length=11)

结果出错:

builtins.TypeError

TypeError: __init__() got an unexpected keyword argument ‘blank’

所以不能乱传入参数,而可以从源码中看到支持有哪些参数:

class CharField(Field):

    def __init__(self, *, max_length=None, min_length=None, strip=True, empty_value=”, **kwargs):

然后去添加试试:

http://localhost:65000/admin/user/user/f92aff51-d1c1-49ed-917e-569da9bfdf1b/change/

很明显地址中的:

f92aff51-d1c1-49ed-917e-569da9bfdf1b

就是新建用户的id

也看到数据库中新增用户了:

【总结】

此处主要就是针对于自己的User的定义,看看新增了哪些字段,然后去对应的UserAdmin的add_fieldsets添加合适的定义即可。

详见代码参考:

【已解决】给Django系统中添加一个新的用户

最后的总结。

转载请注明:在路上 » 【已解决】Django后台管理页面中给新增用户添加自定义字段

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.170 seconds, using 22.08MB memory