Django create custom UserCreationForm

后端 未结 3 1393
失恋的感觉
失恋的感觉 2020-12-08 01:21

I enabled the user auth module in Django, however when I use UserCreationForm it only asks for username and the two password/password confirmation fields. I als

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 01:47

    In django 1.10 this is what I wrote in admin.py to add first_name, email and last_name to the default django user creation form

    from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
    from django.contrib import admin
    from django.contrib.auth.models import Group, User
    
    # first unregister the existing useradmin...
    admin.site.unregister(User)
    
    class UserAdmin(BaseUserAdmin):
        # The forms to add and change user instances
        # The fields to be used in displaying the User model.
        # These override the definitions on the base UserAdmin
        # that reference specific fields on auth.User.
        list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
        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')}),)
        # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
        # overrides get_fieldsets to use this attribute when creating a user.
        add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')}),)
        list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
        search_fields = ('username', 'first_name', 'last_name', 'email')
        ordering = ('username',)
        filter_horizontal = ('groups', 'user_permissions',)
    
    # Now register the new UserAdmin...
    admin.site.register(User, UserAdmin)
    

提交回复
热议问题