Being a Django newbie, I have a question to ask, which should be very simple, but I just can’t figure it out:
I have created a model like the one below:
from django.db import models
from django.core.exceptions import ValidationError
def validate_case_id(value):
if value != "testing":
raise ValidationError("type testing")
class case_form3_tb(models.Model):
case_id = models.CharField(max_length=20, blank=True, null=True, verbose_name="Case ID", validators=[validate_case_id])
wound_others = models.BooleanField(verbose_name="Others")
wound_others_desc = models.CharField(max_length=200, blank=True, null=True, verbose_name="Others (Description)")
I want to validate it in a way that if wound_others is ticked, then wound_others_desc must not be blank.
I just learn how to validate one single text field, but what if the text field is validated based on some other fields?
Thanks.
You should validate at the model level, i.e., write a
clean()method for the model:As a side note, the model name you chose is heavily anti-pythonic. You should always follow the CapWords convention for Python class names.