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

标签 django validation modelform

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

相关文章:

python-3.x - django allauth 中的 Django 排序字段

django - 如何在 Google Cloud App Engine 上使用 PubSub 创建订阅者,通过 Publisher 从 Google Cloud App Engine Flex 收听消息?

javascript - 我可以只使用 jQuery 验证还是需要 PHP?

php - Laravel 验证规则 - 获取损坏的规则名称

php - Codeigniter 房间预订表格验证

django - get_model 相当于 ModelForms 吗?

mysql - Django,查询以获取具有不同名称和最新日期和时间的某些值

mysql - 我如何使用 django migrations.RunSQL 和 MySQL 删除索引(如果存在)

python - 在表单中,如何使用外键显示其他模型的字段,特别是带有选择的字段?

python - Django框架: 'UserView' object has no attribute 'object'