Create custom user form

16,934

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)
Share:
16,934

Related videos on Youtube

bleroy
Author by

bleroy

Updated on September 24, 2022

Comments

  • bleroy
    bleroy over 1 year

    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
    bleroy about 9 years
    Hey @mishbah, the following error occurred: u"Key 'first_name' not found in 'UserForm'"
  • bleroy
    bleroy about 9 years
    I'm still getting the same error: u"Key 'first_name' not found in 'UserForm'"
  • mishbah
    mishbah about 9 years
    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
    mishbah about 9 years
    Please could you post your full stacktrace
  • bleroy
    bleroy about 9 years
    The form is working now! But the username separator is "-". The format I need is first_name.last_name