[Django]-Django models – conditionally set blank=True

9👍

✅

Don’t hate me, but validation is the way to go, see here

class BoolAnswer(models.Model):
    bool_answer_field = models.ForeignKey(BoolAnswerField)
    result = models.BooleanField()
    if_true = models.TextField(max_length=100, null=True, blank=True)

    def clean(self)
        if self.bool_answer_field.if_true_field and not self.if_true:
            raise ValidationError('BAF is True without a reason')

In case you want your error message to be displayed next to the field, not at the beginning of the form, you’ve got to pass a dict to ValidationError, like:

from django.utils.translation import gettext_lazy as _
...
raise ValidationError({
    'field_name': _('This field is required.')})

Leave a comment