验证模型.CharField模型.BooleanField在Django admin中被选中



作为一个Django新手,我有一个问题要问,这个问题应该很简单,但是我就是想不明白:

我已经创建了如下所示的模型:

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

我想以一种方式验证它,如果wound_others被选中,那么wound_others_desc必须不是空的。

我只学习了如何验证一个文本字段,但是如果文本字段是基于其他一些字段验证的呢?

谢谢。

您应该在模型级别进行验证,即,为模型编写一个clean()方法:

def clean(self):
    from django.core.exceptions import ValidationError
    if self.wound_others and not self.wound_others_desc:
        raise ValidationError('Description must not be blank.')

作为旁注,您选择的模型名称是严重反python的。对于Python类名,您应该始终遵循CapWords约定。

最新更新