24

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?

bleroy
  • 311
  • 1
  • 2
  • 8

2 Answers2

41

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)
mishbah
  • 5,487
  • 5
  • 25
  • 35
  • Hey @mishbah, the following error occurred: u"Key 'first_name' not found in 'UserForm'" – bleroy Mar 06 '15 at 11:50
  • I'm still getting the same error: u"Key 'first_name' not found in 'UserForm'" – bleroy Mar 06 '15 at 12:12
  • I don't know where you get error for the `UserForm`. In my example, I'm only overriding the `add_form` which is called `UserCreateForm`. What version of django are you using? – mishbah Mar 06 '15 at 12:16
  • Please could you post your full stacktrace – mishbah Mar 06 '15 at 12:32
  • The form is working now! But the username separator is "-". The format I need is first_name.last_name – bleroy Mar 06 '15 at 13:11
2

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

Karl
  • 146
  • 1
  • 1
  • 12