I've got a Django form class, that inherits from the built-in UserCreationForm.
I'm working on submitting the form using AJAX, and returning the bound form (including errors) as rendered HTML if it doesn't validate.
Something puzzling me is that the errors relating to the password (e.g. too short, common password...) appear for the password2 / confirmation field. Here's a screenshot of the default behaviour:
From a UX perspective I feel as though it would be more useful for the errors to appear for the first password field in the form, so users can adjust that one, then confirm it by typing it again below.
I've noticed that in UserCreationForm, clean_password2(), doesn't actually validate the password, it just checks that password1 and password2 match. Then in the _post_clean() method, password2 is validated, and any errors are added to that field.
In my attempt to change it, I have overridden _post_clean() as follows:
def _post_clean(self):
super(forms.ModelForm, self)._post_clean()
password = self.cleaned_data.get('password1')
if password:
try:
password_validation.validate_password(password, self.instance)
except forms.ValidationError as error:
self.add_error('password1', error)
I don't want to call super, and have it validate and send errors to password2, so I am calling the post_clean method of the grandparent (ModelForm) instead (I think!), to not suffer consequences of leaving anything that does out. Then validating and sending errors to password1 instead.
This is the post_clean() method for UserCreationForm for comparison:
def _post_clean(self):
super()._post_clean()
# Validate the password after self.instance is updated with form data
# by super().
password = self.cleaned_data.get('password2')
if password:
try:
password_validation.validate_password(password, self.instance)
except ValidationError as error:
self.add_error('password2', error)
On the surface this seems to work the way I want it to, but I am not very confident when it comes to overriding methods – I'm scared there will be weird side effects.
So my question is, is this ok? And do you know what I mean about wanting to show the errors for password1 instead? Any advice would be much appreciated!
from Moving password validation errors for Django UserCreationForm, from password2, to password1
No comments:
Post a Comment