4
votes

When creating/adding a user with Django admin; how can this be customized?

For example, currently, the username and password are prompted for. However, I'd like to customize this to also have other required fields, such as 'email'?

The Django tutorial isn't clear on admin user auth customization?

3

3 Answers

9
votes
  1. Place this in your models.py.

    from django.contrib.auth.models import User
    User._meta.get_field('email').blank = False
    
  2. Run makemigrations.

  3. Run migrate.

See the documentation

6
votes

Example for adding email to form when creating a user. In project admin.py added the following:

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _


class UserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password','email')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2', 'email')}
        ),
    )
    form = UserChangeForm
    add_form = UserCreationForm

try:
    admin.site.unregister(User)
except NotRegistered:
    pass

admin.site.register(User, UserAdmin)
0
votes

This is how you can customize the user admin:

from django.contrib import admin
from django.contrib.auth import admin as upstream

# custom admin class for the User model, subclassing Django's one
class UserAdmin(upstream.UserAdmin):
    add_form_template = ...
    add_form = ...
    add_fieldsets = ...

# unregister any existing admin for the User model and register mine
try:
    admin.site.unregister(User)
except NotRegistered:
    pass
admin.site.register(User, UserAdmin)

The parts I left with ... are the customizations you need to do to change the way the admin prompts for user creation.

Look for the original code in django/contrib/auth/admin.py and modify to taste.