Django Modelform - 它没有验证,为什么?

时间:2018-05-21 16:46:12

标签: python django forms django-crispy-forms

我有一个Django modelForm,我试图验证。该字段是一个“自定义”字段 - 即它不是模型中的字段,而是我要解析的两个字段的组合,并检查清理期间是否存在。但是,is_valid()表单方法不起作用,当我打印表单时,它表示有效=未知。

我正在使用Django crispy表格

Forms.py

class SingleSampleForm(forms.ModelForm):

    sample_id = forms.CharField(
        required=True,
        label='Sample ID:')

    class Meta:
        model = Sample
        fields = ('sample_id',)


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

        self.helper = FormHelper()
        self.helper.layout = Layout(

            Field('sample_id',
                # autocomplete='off',
                css_class="search-form-label",
                ),

            Submit('submit', 'Search sample', css_class='upload-btn')
        )
        self.helper.form_method = 'POST'



    def clean_sample_id(self):

        self.sample_id = self.cleaned_data['sample_id']
        print('CLEAN SAMPLE')

        try:
            ... parse self.sample_id and check if exists ...

        except Exception as e:
            return('Sample does not exist')

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):

        sample_form = self.sample_form(request.POST)

        if sample_form.is_valid():
            print('VALID')
            ... HttpRedirect()...

        else:
            print('NOT VALID')
            ... raise error ...

        self.context = {
                'sample_form': sample_form,
            }

        return render(request,
                    'results/single_sample_search.html',
                    self.context)

每次我提交表单字段并尝试验证它时,它会打印'NOT VALID',如果我打印表单,则表示有效=未知。这(几乎)与我的另一种形式完全相同,它允许我清理字段并验证它,即使它们不是特定的模型字段。为什么表格没有验证?

由于

1 个答案:

答案 0 :(得分:0)

您的clean_sample_id函数不会返回任何内容,但它应该返回已清理的值或引发异常。您可以参考下面的代码来检查验证。

def clean_sample_id(self):

    sample_id = self.cleaned_data['sample_id']
    if sample_id:
        return sample_id
    raise ValidationError('This field is required')

请参阅完整文档。 https://docs.djangoproject.com/en/2.0/ref/forms/validation/