Last active
April 23, 2025 12:14
-
-
Save fchabouis/8f92abc043ca450120d7bcfa50b34bdc to your computer and use it in GitHub Desktop.
Django : add email field to user creation form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# context: | |
# You are using the basic User in your Django application | |
# and would like to add the "email" field to the user creation form. | |
# version: tested with Django 5.1.7 | |
# instructions: update admin.py with the following lines | |
from django.contrib.auth.forms import UserCreationForm | |
from django.contrib.auth.models import User | |
from django.contrib import admin | |
from django.contrib.auth.admin import UserAdmin | |
from django import forms | |
# create a new form, adding the email field to the list of fields | |
class CustomUserCreationForm(UserCreationForm): | |
# add this line to make the email field required | |
email = forms.EmailField(required=True) | |
class Meta(): | |
model = User | |
fields = ("username", "email", "password1", "password2") | |
# update the UserAdmin, overriding the "add form" | |
UserAdmin.add_form = CustomUserCreationForm | |
UserAdmin.add_fieldsets = ( | |
(None, { | |
'classes': ('wide',), | |
'fields': ('username', 'email', 'password1', 'password2'), | |
}), | |
) | |
# unregister & re-registger the User, but works fine without doing it | |
#admin.site.unregister(User) | |
#admin.site.register(User, UserAdmin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment