Clean method not called in modelform
As written in the title, the form gets validated whatever happens, I don't understand why are my clean and clean_ methods are not called. Used forms for quite some time but here I am puzzled on what I am forgetting.
Thanks
simplified forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ["workcity", "post_address", "billing_address", "country", "phone"]
def clean(self):
#not called
cleaned_data = super().clean()
billing_address = cleaned_data.get('billing_address')
post_address= cleaned_data.get('post_adress')
if not billing_address == post_address:
do some raising validation error
def clean_workcity(self, *args, **kwargs):
#not called
workcity= self.cleaned_data.get("workcity")
if xxx:
do some raising validation error
return workcity
simplified views.py
def profileform(request):
if request.method =='POST':
form = ProfileForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.save()
messages.success(request, 'Profile created successfully')
return redirect('profile')
else :
handle errors
else:
form = ProfileForm()
return render(request, "CORE/home.html", {"form": form})
I think you got wrong as clean method is called automatically when model save method is called and it is instance method.
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ["workcity", "post_address", "billing_address", "country", "phone"]
def clean(self):
cleaned_data = super().clean()
billing_address = cleaned_data.get('billing_address')
post_address= cleaned_data.get('post_adress')
if not billing_address == post_address:
raise ValidationError({})