在这里处理 django 表单,我遇到了错误。我知道如何检测它们,但我不能(由于某些原因)在不正确的表单下打印错误。
班上 :
class descclient_form(forms.Form):
TYPE_CHOICE = (
('C', ('Client')),
('F', ('Facture')),
('V', ('Visite'))
)
file_type = forms.ChoiceField(choices = TYPE_CHOICE, widget=forms.RadioSelect)
file_name = forms.CharField(max_length=200)
file_cols = forms.CharField(max_length=200, widget=forms.Textarea)
# file_date = forms.DateField()
file_sep = forms.CharField(max_length=5, initial=';')
file_header = forms.CharField(max_length=200, initial='0')
# Check if file_cols is correctly filled
def clean_cols(self):
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:
self._errors['file_cols'] = [u'Requiers \'Client\' in collumn selection']
print 'error'
if cleaned_file_type == 'F':
mandatory_field = ('fact', 'caht', 'fact_dat')
for mf in mandatory_field:
if mf not in cleaned_file_cols:
self._errors["file_cols"] = self.error_class(['Requiers \'fact\', \'caht\' \'fact_dat\ in file_cols'])
print 'error'
return self.cleaned_data
这是调用的函数:
def descclient(request):
if request.method == 'POST':
form = descclient_form(data=request.POST)
if form.is_valid():
form.clean_cols()
return render_to_response('descclient.html', {'form': descclient_form}, context_instance=RequestContext(request))
和模板:
<form action="/descclient" method="post">
<div class="fieldWrapper">
{{ form.file_type_errors }}
<label for="id_subject">File type:</label>
{{ form.file_type }}
</div>
<div class="fieldWrapper">
{{ form.file_name_errors }}
<label for="id_subject">File name:</label>
{{ form.file_name }}
</div>
<div class="fieldWrapper">
{{ form.file_cols_errors }}
<label for="id_subject">Collumns:</label>
{{ form.file_cols }}
</div>
<div class="fieldWrapper">
{{ form.file_sep_errors }}
<label for="id_subject">Separator:</label>
{{ form.file_sep }}
</div>
<div class="fieldWrapper">
{{ form.file_header_errors }}
<label for="id_subject">Header:</label>
{{ form.file_header }}
</div>
{% csrf_token %}
<p><input type="submit" value="Validate"></p>
对于某些原因,“{{ form.file_cols_errors }}”不打印任何内容
编辑 :
因此,正如所指出的,我将 clean_cols 方法更改为 clean。我一定是迷路了,因为它甚至没有进入 if 语句
def clean(self):
cleaned_data = super(descclient_form, self).clean()
cleaned_file_type = cleaned_data("file_type")
cleaned_file_cols = cleaned_data("file_cols")
if cleaned_file_type == 'C':
if 'client' not in cleaned_file_cols:
raise forms.ValidationError("This field throws an error")
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("This field throws an error")
return cleaned_data