为什么这个django形式无效?

时间:2018-05-22 12:49:10

标签: python django forms

为什么这个表格没有验证?它甚至没有调用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')

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)

我不明白为什么它甚至没有调用clean()方法。我有另一种几乎相同的形式,它有效。在我通过print dir(self.sample_form)字典后{I} request.POST时,它会指出validation=unknown。为什么是这样?如何查看未验证的原因?

1 个答案:

答案 0 :(得分:8)

致电*args时,您需要传递**kwargssuper()

def __init__(self, *args, **kwargs):
    super(SingleSampleForm, self).__init__(*args, **kwargs)

目前,在没有任何__init__*args的情况下拨打**kwargs等同于使用data=None进行呼叫。表单未绑定,因此永远无效。