Skip to content
Advertisement

Django Model Form doesn’t seem to validate the BooleanField

In my model the validation is not validating for the boolean field, only one time product_field need to be checked , if two time checked raise validation error.

product_field = models.BooleanField(default=False)
       def clean(self):
            if (self.product_field is not None).count() < 1:
               raise ValidationError(
                    {
                       "product_field": _(" Product field can be select once")
                     }
                 )

Advertisement

Answer

Boolean and None are not always the same. I think that is the root of your problem. Here is None vs False:

# python3
> False is None
False

I find the code and information confusing.

I assume product_filed is a typo. Generally models.BooleanField have to possibilities True and False. If blank=True and required=False are set then None can happen (unset aka NULL).

Keep the default=False and don’t check for None, you should never see None with a default on a Bool.

You mention if two time checked raise validation error – Huh? This is also confusing. What are you trying to accomplish? The logic and details do not make complete sense to me.

To check the bool you can use if not self.product_field: … raise.

What is being counted?

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement