覆盖一个django表单元素上的数据验证 [英] Override data validation on one django form element
问题描述
第一个列表的第一个元素是所有董事。而不是过滤电影列表,它可以让所有的电影都显示在第二个列表中,因为所有的董事被选中。
如果用户选择一个特定的导演,然后一个电影,表单提交正确。问题是,如果用户选择所有董事,然后选择电影,当提交表单时,它告诉我,我对董事的选择无效,因为它不是可用的选择之一。在这种情况下,可用的选择(我假设)是数据库中现有的Director.object之一。但是因为我不在乎导演,所以我不需要这个条目是有效的。我只需要电影才能有效。
我正在使用一个ModelForm。 如何禁用或覆盖Director表单字段中的数据验证,以便忽略该字段生成的错误。
最简单的方法是定义自己的方法来验证表单,如下所示:
class MyForm(forms.ModelForm):
class Meta:
model = WhateverModel
def clean(self):
super(MyForm,self).clean()如果需要,
如果self.cleaned_data.get('film')和'director'in self._errors:
del self._errors ['director']
return self.cleaned_data
请参阅 http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-和验证字段 - 依赖每个其他 fo更广泛的解释和 http:// docs .djangoproject.com / en / dev / topics / forms / modelforms /#overriding-the-clean-method 如何应用于ModelForms。
I have a select list dropdown box on my form that is populated with data from a Model (Directors). The value of this dropdown doesn't need to be saved; it is really only used to dynamically trigger another element of the form (a dropdown titled Films). So when the user chooses a Director, it dynamically populates the second list with the Films attached to that Director.
The first element of the first list is "All Directors." Instead of filtering the Film List, it lets all Films be shown on the second list because All Directors is chosen.
If the user chooses a specific Director and then a Film, the form submits correctly. The problem is that if the user chooses All Directors, and then selects a Film, when the form is submitted, it tells me that my choice for Directors is not valid because it is not one of the available choices. In this instance, an available choice (I assume) is one of the existing Director.objects that is in the database. But because I don't care about the Director, I don't need this entry to be valid. I just need Film to be valid.
I'm using a ModelForm. How can I disable or override the data validation on the Director form field so that it ignores the error that that field generates?
The easiest approach would be to define your own method for validating the form, like this:
class MyForm(forms.ModelForm):
class Meta:
model = WhateverModel
def clean(self):
super(MyForm, self).clean() #if necessary
if self.cleaned_data.get('film') and 'director' in self._errors:
del self._errors['director']
return self.cleaned_data
See http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other for a more extensive explanation and http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method for how it applies to ModelForms.
这篇关于覆盖一个django表单元素上的数据验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!