我有以下模型表单,想要将自定义验证添加到名为“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/