Reputation: 12173
I am trying to build an app, where user can customize forms. The Following example contains classes for creating Fields (QuestionField
, AnswerField
) which is used by the admin and the BoolAnswer
which is filled by the user: This Way an admin can create a Form with questions and possible answers.
According to django documentation, blank=True
is related to evaluation. The problem is that it is set on the class level rather than on object level.
How can I set blank=True
depending on the related model so that I do not have to reimplement an own validator? (see pseudo code in BoolAnswer
)
My models.py
:
class QuestionField(models.Model):
question = models.TextField(max_length=200)
models.ForeignKey(Sheet)
class BoolAnswerField(AnswerField):
question = models.ForeignKey(models.Model)
if_true_field = models.TextField(max_length=100, null=True)
class BoolAnswer(models.Model):
bool_answer_field = models.ForeignKey(BoolAnswerField)
result = models.BooleanField()
if_true = models.TextField(max_length=100, null=True,
blank=True if self.bool_answer_field.if_true_field)
** Short explanation **:
If the Answer to a BoolAnswerField
question is True, if_true
field should explain, why
Upvotes: 3
Views: 2122
Reputation: 4129
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.')})
Upvotes: 9