tro*_*ife 3 python forms django
为什么这个表格没有验证?它甚至没有调用该clean()
方法.
forms.py:
class SingleSampleForm(forms.Form):
sample_id = forms.CharField(label='Sample ID:')
class Meta:
fields = ('sample_id',)
def __init__(self, *args, **kwargs):
super(SingleSampleForm, self).__init__()
self.helper = FormHelper()
self.helper.layout = Layout(
Field('sample_id',
css_class="search-form-label",),
Submit('submit', 'Search sample', css_class='upload-btn')
)
self.helper.form_method = 'POST'
def clean(self):
print('CLEAN')
sample_id = self.cleaned_data['sample_id']
if sample_id:
return sample_id
raise ValidationError('This field is required')
Run Code Online (Sandbox Code Playgroud)
views.py:
class SampleView(View):
sample_form = SingleSampleForm
def get(self, request, *args, **kwargs):
sample_form = self.sample_form()
self.context = {'sample_form': sample_form,}
return render(request,
'results/single_sample_search.html',
self.context)
def post(self, request, *args, **kwargs):
self.sample_form = self.sample_form(request.POST)
if self.sample_form.is_valid():
print('Valid')
else:
print('not valid')
self.context = {
'sample_form': self.sample_form,
}
return render(request,
'results/single_sample_search.html',
self.context)
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它甚至没有调用该clean()
方法.我有另一种几乎相同的形式,它有效.在我print dir(self.sample_form)
通过该request.POST
词典后,当我这样做时,它说明了这一点validation=unknown
.为什么是这样?如何查看未验证的原因?
你需要传递*args
和**kwargs
当你调用super()
:
def __init__(self, *args, **kwargs):
super(SingleSampleForm, self).__init__(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
此刻,呼叫__init__
没有任何*args
或**kwargs
等同于呼叫data=None
.表单未绑定,因此永远无效.