form.is_valid() return true when its false

Hi,

I can’t explain why because I didnt override clean function but when I post a form.
the is_valid() function return true when it’s false raising ValueError : The EntreeEau could not be created because the data didn’t validate.

my model :

class EntreeEau(Marker):
    
    identification = models.CharField(max_length=30, blank=False, unique=True)  # La validation ne sera pas la meme que Commerciale
    type = models.IntegerField(default=EE_Type.RESIDENTIEL, choices=EE_Type)
    related_adresse = models.ForeignKey(CivicAdresse, on_delete=models.SET_NULL, null=True, blank=True)
    dimension = models.IntegerField(default=EE_Dimension._3_4po, choices=EE_Dimension)
    mat_type = models.IntegerField(default=EE_Mat_type.CUIVRE, choices=EE_Mat_type)

    def label(self):
        return self.type.label

    def __str__(self):
        return self.identification

    def __unicode__(self):
        return self.identification
    
    class Meta:
        verbose_name = "Entree d'eau"
        verbose_name_plural = "Entre d'eau"

my form:

class EntreEauResidentielForm(forms.ModelForm):
    class Meta:
        model = EntreeEau

        fields = [
            'latitude',
            'longitude',
            'note',
            'identification',
            'related_adresse',
            'dimension',
            'mat_type'
        ]

    def __init__(self,loggedin_user, *args, **kwargs):
        super(EntreEauResidentielForm, self).__init__(*args, **kwargs)  
        self.fields['related_adresse'].queryset = CivicAdresse.objects.filter(locality = loggedin_user.ville.id )

my view :

class AddNewEER(View):
    def post(self, request, *args, **kwargs):
        form = EntreEauResidentielForm(request.user,request.POST, prefix='EER')
        if form.is_valid:
            instance = form.save(commit=False)
            instance.type = EE_Type.RESIDENTIEL
            instance.related_client = request.user.ville
            instance.save()
            response = {}
            response['success']= True
            response['message'] = "L'entrée d'eau est ajouté avec succès."
            
            return JsonResponse(response, safe=False)
        else:
            return JsonResponse({'success': False, 'message': form.errors})

if the data is truly valid, the models object get created.

I tried with already existing identification field. This field is unique.

any clue ?

The is_valid attribute of a form is a function. You need to call it.

Oh damn, my bad. I’ll take a break.

thank you!

Just to add a bit more, on why you’re receiving a “True” (you’re not receiving actually a True, but a “truthy” value).
When you do the following check:
if form.is_valid:
What’s happening under the hood, is something like (pseudo-code):

# Evaluate form.is_valid, python will try to the get the attribute `is_valid` from the `form` object
condition = form.is_valid
# if this attribute didn't exist python would throw an AttributeError. But the attribute does exist.
# form.is_valid is represented as a "callable" attribute/object. But this callable is also an object. It has a lot of attributes.
# So when you do the below
if condition:
# What's happening is that python is calling something like:
if bool(condition):
# and since the attribute is a object, it will be resolved to a True value in that situation.

So this sometimes is tricky, in programming in general. But don’t feel bad about it, it happens anytime to anybody.
I hope that understanding the concept that I have shown above help on the next time you face something similar (you will haha).

1 Like