【问题标题】:Missing cleaned_data in forms (django)表单中缺少cleaned_data(django)
【发布时间】:2012-07-13 13:25:32
【问题描述】:

我想创建一个表单和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 一直告诉我他没有重新整理cleaned_data。我知道我错过了有关文档或其他内容的信息,但我无法理解是什么。请帮忙!

【问题讨论】:

    标签: python django forms


    【解决方案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

    【讨论】:

    • 感谢您的建议,但由于某种原因,当我重命名它以清理它时,当我调用 contact_form.is_valid() 时它没有被调用?
    • 在您看来,您还没有将表单绑定到任何数据,因此不会调用 clean 方法。你需要例如contact_form = ContactForm(request.POST)。请参阅docs 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2010-10-12
    • 1970-01-01
    • 2011-05-18
    相关资源
    最近更新 更多