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

Django Modelform - it is not validating, why?

我有一个正在尝试验证的 Django modelForm。该字段是一个 'custom' 字段 - 即它不是模型中的字段,而是我想要解析并检查清理期间是否存在的两个字段的组合。但是 is_valid() 表单方法不起作用,当我打印表单时它说 valid=unknown。

我正在使用 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)

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

谢谢

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

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/