In this interface I want to add first name and last name field. I know those fields are already present as optional fields in django.contrib.auth.models User model, but they don't show up in UI. Also to make those fields required, is it necessary to override existing User model? I am new to this and have a feeling that doing so would not be a good idea. All help is appreciated!
Asked
Active
Viewed 677 times
1 Answers
0
Subclass the UserCreationForm
and use it in your custom user admin:
# forms.py
from django.contrib.auth.forms import UserCreationForm
class CustomUserCreationForm(UserCreationForm):
# make fields required if desired
# first_name = forms.CharField(required=True)
class Meta(UserCreationForm.Meta):
fields = ("username", "first_name", "last_name")
# admin.py
from django.contrib.admin.sites import site
from django.contrib.auth.admin import UserAdmin
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2',
'first_name', 'last_name'),
}),
)
site.unregister(User)
site.register(User, CustomUserAdmin)

user2390182
- 72,016
- 6
- 67
- 89
-
Unfortunately this didn't work, after applying migrations and running server again, UI is still same as before....what could possibly have gone wrong? – Madhur Gupta Apr 02 '20 at 07:07
-
Also, I am unable to add any new users now. I get message "Please correct the errors below." but it doesn't even show any error – Madhur Gupta Apr 02 '20 at 07:15
-
Added the `add_fieldsets` attribute. See also https://stackoverflow.com/questions/28897480/django-admin-custom-create-user-form/28897968 – user2390182 Apr 02 '20 at 07:26
-
Ok, will try that one – Madhur Gupta Apr 02 '20 at 07:31