bleroy
bleroy

Reputation: 311

Create custom user form

On Django Admin, the default 'create user' form has 3 fields: username, password and confirm password.

I need to customize the create user form. I want to add the firstname and lastname fields, and autofill the username field with firstname.lastname.

How can I do this?

Upvotes: 24

Views: 20907

Answers (2)

Himalaya Dave
Himalaya Dave

Reputation: 23

Only add_fieldsets is enough. No need to provide the add_form.

this would be the full code for admin.py, you can read about it in the Django docs here

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

class UserAdmin(UserAdmin):
    add_fieldsets = (
            (
                None,
                {
                    'classes': ('wide',),
                    'fields': ('username', 'email', 'password1', 'password2'),
                },
            ),
        )

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

As a side note: 'classes':('wide',), sets the style of the field to open or "not collapsed", you can read more about the options for that here

Upvotes: 2

mishbah
mishbah

Reputation: 5597

Something like this should work:

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

class UserCreateForm(UserCreationForm):

    class Meta:
        model = User
        fields = ('username', 'first_name' , 'last_name', )


class UserAdmin(UserAdmin):
    add_form = UserCreateForm
    prepopulated_fields = {'username': ('first_name' , 'last_name', )}

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name', 'username', 'password1', 'password2', ),
        }),
    )


# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Upvotes: 41

Related Questions