Django模型 - 有条件地设置blank=True

3
我正在尝试构建一个应用程序,用户可以自定义表单。以下示例包含用于创建字段(QuestionFieldAnswerField)的类,管理员和用户使用BoolAnswer填充:这样管理员就可以创建带有问题和可能答案的表单。
根据Django文档,blank=True与评估相关。问题在于它设置在类级别而不是对象级别。
我如何根据相关模型设置blank=True,以便我不必重新实现自己的验证器?(请参见BoolAnswer中的伪代码)
我的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)

** 简要说明 **: 如果BoolAnswerField问题的答案为True,则if_true字段应该解释原因。

1个回答

9

不要讨厌我,但是验证是可行的方式,参见这里

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')

如果您想要将错误信息显示在字段旁边,而非表单开头,则需要向ValidationError传递一个dict,例如:

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

我认为你是对的,只是我以为我需要在表单级别上进行自定义验证。 - ProfHase85
1
最好在模型中进行此验证,以便您可以使用ModelForm(它会更改正在验证的实例/不建议覆盖ModelForm.clean())。 - ron_g

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接