4

当另一个 [关联] 字段具有特定值时,如何使必填字段成为非必填字段?

假设我有以下模型:

class foo(models.Model):
    bar = models.CharField(max_length=200)
    foo_date = models.DateTimeField()

当我保存并且 bar 包含某个值时,我希望 foo_date 成为非强制性的。我该如何做到这一点?谢谢。

4

2 回答 2

3

T.Stone 是对的。这是您使用模型表单的方式:

class foo(models.Model):
    bar = models.CharField(max_length=200)
    foo_date = models.DateTimeField()

class ClientAdmin( MyModelAdmin ):
    form = FooModelForm

class FooModelForm( forms.ModelForm ):

    def clean(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.get("bar") == 'some_val' and not cleaned_data.get('foo_date'):
            msg = 'Field Foo Date is mandatory when bar is some_val'
            self._errors[field] = ErrorList([msg])
            del cleaned_data[field]
        return cleaned_data

http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

于 2009-09-11T13:22:11.290 回答
2

我认为只需将 foo_barr 设置为 blank=True,然后实现您自己的表单和自定义验证以供 Admin 模型使用。请参阅文档的这一部分——向管理员添加自定义验证

于 2009-09-10T22:45:03.910 回答