Make it easier to extend UserCreationForm for custom user models
|Reported by:||Baptiste Mispelon||Owned by:||Berker Peksag|
|Cc:||Russell Keith-Magee, aenor.realm@…, Mjumbe Poe, victorhooi@…, internet@…, flisky, maestrofjp, berker.peksag@…||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
The documentation 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:
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
To get it working, the original
clean_username method needs to be copied over and modified to use the custom user model, like so:
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
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.
Change History (24)
comment:20 Changed 10 months ago by
|Owner:||changed from nobody to Berker Peksag|
|Status:||new → assigned|