gpt4 book ai didi

Django ModelForm自定义验证: How to access submitted field values

转载 作者:行者123 更新时间:2023-12-02 08:10:04 25 4
gpt4 key购买 nike

我有以下模型表单,想要将自定义验证添加到名为“bilable_work”的字段。

如何访问在表单中提交的“项目”字段?我想检查项目的值(下面示例中的“p”),但无法找到正确的语法,以便我可以测试提交的值。任何帮助将不胜感激。

class EntryForm(forms.ModelForm):
class Meta:
model = Entries
exclude = ('billable_work','notes')

billable_work = forms.BooleanField()
notes = forms.CharField(widget=forms.Textarea,required=False)

def clean_billable_work(self):
b = self.cleaned_data['billable_work']
p = form.fields['project']

if b == True and p == 523:
raise forms.ValidationError(_("Entries cannot be both billable and NONE: Indirect."))
return self.cleaned_data['billable_work']

最佳答案

我想你想覆盖 clean()模型上的方法而不是特定表单字段的干净方法。来自文档 -

This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field.

如果您确实想将验证放入表单中,则表单上的 clean() 方法可提供类似的功能(请参阅 docs )。

关于Django ModelForm自定义验证: How to access submitted field values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15095234/

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