#19353: Make it easier to extend UserCreationForm for custom user models
----------------------------+----------------------------------------------
Reporter: bmispelon | Owner: nobody
Type: New | Status: new
feature | Version: 1.5-alpha-1
Component: | Keywords: UserCreationForm AUTH_USER_MODEL
contrib.auth | Has patch: 0
Severity: Normal | UI/UX: 0
Triage Stage: Unreviewed |
Easy pickings: 0 |
----------------------------+----------------------------------------------
The documentation [https://docs.djangoproject.com/en/dev/topics/auth
/#custom-users-and-the-built-in-auth-forms states] that `UserCreationForm`
must be re-written when using a custom user model.
However, for simple subclasses of `AbstractUser` it's actually simpler to
extend (rather than rewrite) the existing form like so:
{{{
#!python
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
}}}
Unfortunately, this fails because the `clean_username` method of
`UserCreationForm` still references the original `User` model directly
(this technique works with `UserChangeForm` though).
To get it working, the original `clean_username` method needs to be copied
over and modified to use the custom user model, like so:
{{{
#!python
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
def clean_username(self):
username = self.cleaned_data["username"]
try:
CustomUser.objects.get(username=username)
except CustomUser.DoesNotExist:
return username
raise
forms.ValidationError(self.error_messages['duplicate_username'])
}}}
This works, but having to copy/paste some code is not a very good
practice.
Therefore, I propose to change `UserCreationForm.clean_username` to use
`Meta.model` instead of `User`.
This allows the creation of custom user creation forms by simply
redefining the user model in the form's `Meta` class (like in the first
example).
The documentation could also be extended to show an example of how to
extend the builtin auth forms that require it.
--
Ticket URL: <https://code.djangoproject.com/ticket/19353>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.