Marco Fedele
Marco Fedele

Reputation: 2148

Django Fomset is_valid() fails with no errors

I'm building a formset basing on a custom ModelForm and a custom validation.

The problem is that validation fails with no errors.

Here is the custom ModelForm and Formset:

 class AlternateFloorForm(ModelForm):
         class Meta:
                 model = Floor
                 exclude = ('id_edificio', 'numero_di_piano', 'link', 'id')

                 widgets = {
                         'bearing' : HiddenInput(),
                         'zoom_on_map' : HiddenInput(),
                         'posizione_immagine' : HiddenInput(),
                 }  

 class BaseAlternateFloorFormSet(BaseFormSet):

         def clean(self):
                 if any(self.errors):
                         return

                 for i in range(0, self.total_form_count()):
                         form = self.forms[i]
                         bearing = form.cleaned_data.get('bearing', None)
                         if (bearing != None) or (bearing < 0) or (bearing > 360):
                                 raise forms.ValidationError("Bearing is not correct!!!")

I have tried also with only one form, but is_valid() is always False, and field.errors field.non_field_errors show nothing.

Upvotes: 0

Views: 460

Answers (2)

Marco Fedele
Marco Fedele

Reputation: 2148

So, I was missing a

 return self

in the form validation, as told from Raunak Agarwal, and I was using an incorrect method for returning errors as told from Mark Lavin.

But over to all is that

 if (bearing != None) or (bearing < 0) or (bearing > 360):

is returning always False. This is the correct condition:

 if (bearing == None) or (bearing < 0) or (bearing > 360):

Thanks to all!

Upvotes: 0

Raunak Agarwal
Raunak Agarwal

Reputation: 7228

You are missing return cleaned_data

Upvotes: 1

Related Questions