Django composition clean forms don't work correctly
class RegisterForm(forms.ModelForm):
...
class Meta:
model = CreateUser
...
def clean(self, password1, password2, error_key="password"):
symbols = ['$', '@', '#', '%', '!']
password1 = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
errors = dict()
if password1 and password2:
if password1 != password2:
errors[error_key] = "Passwords do not match"
raise forms.ValidationError(errors)
if not any(symbol in symbols for symbol in password1):
s = ", "
errors[error_key] = f"Passwords don\'t have symbols like {s.join(symbols)}"
raise forms.ValidationError(errors)
if not any(char.isdigit() for char in password1):
errors[error_key] = "Password should have at least one numeral"
raise forms.ValidationError(errors)
if not any(char.isupper() for char in password1):
errors[error_key] = "Password should have at least one uppercase letter"
raise forms.ValidationError(errors)
if not any(char.islower() for char in password1):
errors[error_key] = "Password should have at least one lowercase letter"
raise forms.ValidationError(errors)
return self.cleaned_data
class SetPasswordsForm(forms.Form):
...
def __init__(self, user, *args, **kwargs):
self.user = user
self.register = RegisterForm
super().__init__(*args, **kwargs)
def clean(self):
password1 = self.cleaned_data.get('new_password')
password2 = self.cleaned_data.get('confirm_new_password')
self.register.clean(self, password1, password2, error_key="new_password")
return self.cleaned_data
I want composition class and function and override this in django, I created my own User, and now i created my own validation but i dont want duplicate code-lines. Why this second function clean don't work correctly? ;/
On this line you call the clean RegisterForm method.
self.register.clean(self, password1, password2, error_key="new_password")
But you create the form and you don't set the data, and the form has no data to validate:
class SetPasswordsForm(forms.Form):
def __init__(....):
self.register = RegisterForm
Additionally, the RegisterForm's clean method sets parameters that are then overwritten with the values from cleaned_data
. Obviously, these parameters has no effect:
def clean(self, password1, password2, error_key="password"):
symbols = ['$', '@', '#', '%', '!']
password1 = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
Don't reinvent the wheel. Use the tools provided by Django. If you need write forms validators and reuse the code, you can start here: https://docs.djangoproject.com/en/3.2/ref/validators/