python – 表单中缺少cleaning_data(django)
发布时间:2020-12-20 13:29:03 所属栏目:Python 来源:网络整理
导读:我想创建一个表单和validation_forms,如果正确检查了另一个框,将检查某个文本是否在框中出现, class Contact_form(forms.Form):def __init__(self): TYPE_CHOICE = ( ('C',('Client')),('F',('Facture')),('V',('Visite')) ) self.file_type = forms.ChoiceF
我想创建一个表单和validation_forms,如果正确检查了另一个框,将检查某个文本是否在框中出现,
class Contact_form(forms.Form): def __init__(self): TYPE_CHOICE = ( ('C',('Client')),('F',('Facture')),('V',('Visite')) ) self.file_type = forms.ChoiceField(choices = TYPE_CHOICE,widget=forms.RadioSelect) self.file_name = forms.CharField(max_length=200) self.file_cols = forms.CharField(max_length=200,widget=forms.Textarea) self.file_date = forms.DateField() self.file_sep = forms.CharField(max_length=5,initial=';') self.file_header = forms.CharField(max_length=200,initial='0') def __unicode__(self): return self.name # Check if file_cols is correctly filled def clean_cols(self): #cleaned_data = super(Contact_form,self).clean() # Error apears here cleaned_file_type = self.cleaned_data.get(file_type) cleaned_file_cols = self.cleaned_data.get(file_cols) if cleaned_file_type == 'C': if 'client' not in cleaned_file_cols: raise forms.ValidationError("Mandatory fields aren't in collumn descriptor.") if cleaned_file_type == 'F': mandatory_field = ('fact','caht','fact_dat') for mf in mandatory_field: if mf not in cleaned_file_cols: raise forms.ValidationError("Mandatory fields aren't in collumn descriptor.") def contact(request): contact_form = Contact_form() contact_form.clean_cols() return render_to_response('contact.html',{'contact_form' : contact_form}) 不幸的是,django一直在告诉我他没有重新认识clean_data.我知道我已经错过了关于doc或者某些东西的东西,但我无法明白什么.请帮忙 ! 解决方法
验证单个字段时,clean方法应具有表单的名称
clean_<name of field> 例如clean_file_col.然后,当您在视图中执行form.is_valid()时,它将自动调用. 命名方法clean_cols表明你有一个名为cols的字段,这可能会引起混淆. 在这种情况下,你的validation relies on other fields,所以你应该重命名clean_col方法简单地清理.这样,它将自动调用. def clean(self): cleaned_data = super(Contact_form,self).clean() cleaned_file_type = self.cleaned_data.get(file_type) # ... 最后,在您看来,您还没有将表单绑定到任何数据, contact_form = Contact_form() 所以contact_form.is_valid()将始终返回False.您需要使用form = ContactForm(request.POST)将表单绑定到post数据.有关完整示例和说明,请参阅Django docs for using a form in a view. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |