This should be as simple as overriding the behavior of the User ModelAdmin class. In one of your apps, in admin.py
include the following code.
from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class MyUserCreationForm(UserCreationForm):
username = forms.RegexField(
label='Username',
max_length=30,
regex=r'^[\w-]+$',
help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
error_message = 'This value must contain only letters, numbers, hyphens and underscores.')
class MyUserChangeForm(UserChangeForm):
username = forms.RegexField(
label='Username',
max_length=30,
regex=r'^[\w-]+$',
help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
error_message = 'This value must contain only letters, numbers, hyphens and underscores.')
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
Here's a little explanation.
The first class definition (MyUserCreationForm) is a subclass (yes your terminology is correct) of the UserCreationForm. This is the form that appears when you click "Add User" in the Django Admin site. All we are doing here is redefining the username
field to use our improved, hyphen-accepting regex, and changing the helptext
to reflect this.
The second class definition does the same, except for the UserChangeForm.
The final class definition is a subclass of UserAdmin, which is the ModelAdmin that the User model uses by default. Here we state that we want to use our new custom forms in the ModelAdmin.
Note that for each of these subclasses, we only change what we have to. The rest of the class will be inherited from its parent (UserCreationForm, UserChangeForm and UserAdmin respectively).
Finally, we perform the important step of registering the User model with the admin site. To do that we unregister the default UserAdmin, and then register with our improved MyUserAdmin class.
You'll find that the Django admin site is very easy to customize using these techniques, especially considering the admin site is just a regular Django app.