当另一个[关联]字段具有特定值时,如何使必填字段成为非必需字段?
我们假设我有以下模型:
class foo(models.Model):
bar = models.CharField(max_length=200)
foo_date = models.DateTimeField()
当我保存,并且bar包含某个值时,我希望foo_date成为非强制性的。我该如何做到这一点?感谢。
答案 0 :(得分:3)
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
答案 1 :(得分:2)
我认为只需将foo_barr设置为blank = True,然后为Admin模型实现自己的Form和自定义验证即可。请参阅文档的这一部分 - Adding custom validation to admin