gpt4 book ai didi

python - 表单中缺少 cleaned_data (django)

转载 作者:太空宇宙 更新时间:2023-11-03 11:55:36 31 4
gpt4 key购买 nike

我想创建一个表单和 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。我知道我错过了有关文档的某些内容或其他内容,但我无法理解是什么。请帮忙!

最佳答案

当验证一个单独的字段时,你的 clean 方法应该有一个表单的名称

clean_<name of field>

例如 clean_file_col。然后,当您在 View 中执行 form.is_valid() 时,它将被自动调用。

将您的方法命名为 clean_cols 表明您有一个名为 cols 的字段,这可能会引起混淆。

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

def clean(self):
cleaned_data = super(Contact_form, self).clean()
cleaned_file_type = self.cleaned_data.get(file_type)
# ...

最后,在您看来,您还没有将表单绑定(bind)到任何数据,

contact_form = Contact_form()

所以 contact_form.is_valid()总是返回 False。您需要使用 form = ContactForm(request.POST) 将表单绑定(bind)到发布数据。查看Django docs for using a form in a view一个完整的例子和解释。

关于python - 表单中缺少 cleaned_data (django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471431/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com