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)
Related videos on Youtube
Author by
bleroy
Updated on September 24, 2022Comments
-
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
andlastname
fields, and autofill the username field withfirstname.lastname
.How can I do this?
-
bleroy about 9 yearsHey @mishbah, the following error occurred: u"Key 'first_name' not found in 'UserForm'"
-
bleroy about 9 yearsI'm still getting the same error: u"Key 'first_name' not found in 'UserForm'"
-
mishbah about 9 yearsI don't know where you get error for the
UserForm
. In my example, I'm only overriding theadd_form
which is calledUserCreateForm
. What version of django are you using? -
mishbah about 9 yearsPlease could you post your full stacktrace
-
bleroy about 9 yearsThe form is working now! But the username separator is "-". The format I need is first_name.last_name