gpt4 book ai didi

Django modelform 根据其他字段选择删除 "required"属性

转载 作者:行者123 更新时间:2023-12-04 10:20:54 26 4
gpt4 key购买 nike

我有几个字段的 ModelForm。有些字段是必需的,有些则不是。此外,我有具有不同选择的 Select 字段,我想根据此 Select 字段选择使某些字段“必填”或不“必填”。

我在 Form 的 clean() 方法中尝试过

def clean(self):
cleaned_data = self.cleaned_data
some_field = cleaned_data.get("some_field")
if some_field == 'some_value':
self.fields['other_field'].required = False
return cleaned_data

但它不起作用

最佳答案

请参阅 Cleaning and validating fields that depend on each other 上的 Django 文档.标准做法是执行以下处理:

def clean(self):
cleaned_data = self.cleaned_data
some_field = cleaned_data.get("some_field")
if some_field == 'some_value':
# 'other_field' is conditionally required.
if not cleaned_data['other_field']:
raise forms.ValidationError("'Other_field' is required.")
return cleaned_data

关于Django modelform 根据其他字段选择删除 "required"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7092536/

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