gpt4 book ai didi

Django 管理员 : Making mandatory fields non-mandatory dynamically

转载 作者:行者123 更新时间:2023-12-01 00:05:52 24 4
gpt4 key购买 nike

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

假设我有以下模型:

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

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

最佳答案

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

关于Django 管理员 : Making mandatory fields non-mandatory dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1407160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com