表格中缺少cleaning_data(django)

时间:2012-07-13 13:25:33

标签: python django forms

我想创建一个表单和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})

Infortunatly,django一直告诉我他没有重新清理cleaning_data。我知道我已经错过了关于doc或者某些东西的东西,但我无法明白什么。请帮忙!

1 个答案:

答案 0 :(得分:1)

验证单个字段时,clean方法的名称应为

clean_<name of field>

例如clean_file_col。然后,当您在视图中执行form.is_valid()时,系统会自动调用它。

命名方法clean_cols表示您有一个名为cols的字段,这可能会导致混淆。

在这种情况下,您的validation relies on other fields,因此您应该将clean_col方法重命名为clean。这样,当您在视图中执行form.is_valid()时,系统会自动调用它。

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)将表单绑定到帖子数据。有关完整示例和说明,请参阅Django docs for using a form in a view