Django Validation with and or rule

69 Views Asked by At

The condition supposed to be only if this field is filled other field do not need to filled. Now with this code i have to fill out all the fields.

 if (self.start==None and self.end==None) or (self.running==None  and self.walking==None ) :
        raise ValidationError(
            {
                "start": _("Need to be filled"),
                 "end": _("Need to be filled"),
                "running": _("Need to be filled"),
                "walking": _("Need to be filled")
            }
        )
1

There are 1 best solutions below

15
On BEST ANSWER

Try this:

if self.start==None and self.end==None and self.running==None and self.walking==None:
   raise ValidationError(
            {
                "start": _("Need to be filled"),
                "end": _("Need to be filled"),
                "running": _("Need to be filled"),
                "walking": _("Need to be filled")
            }
        )

if (self.start!=None or self.end!=None) and (self.running!=None or self.walking!=None):
   raise ValidationError(
            {
                "running": _("Don't need to be filled"),
                "walking": _("Don't need to be filled")
            }
        )

if self.start!=None and self.end==None:
   raise ValidationError(
            {
                "end": _("Need to be filled")
            }
        )

if self.start==None and self.end!=None:
   raise ValidationError(
            {
                "start": _("Need to be filled")
            }
        )

if self.running!=None and self.walking==None:
   raise ValidationError(
            {
                "walking": _("Need to be filled")
            }
        )

if self.running==None and self.walking!=None:
   raise ValidationError(
            {
                "running": _("Need to be filled")
            }
        )