Make it easier to extend UserCreationForm for custom user models
|Reported by:||bmispelon||Owned by:||nobody|
|Cc:||russellm, aenor.realm@…, mjumbewu, victorhooi@…, internet@…, flisky, maestrofjp||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||yes|
|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 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:
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.
Change History (16)
comment:1 Changed 3 years ago by bmispelon
- Has patch set
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:4 Changed 3 years ago by russellm
- Needs documentation set
- Triage Stage changed from Unreviewed to Accepted