gpt4 book ai didi

python - 为什么这个 django 表单无效?

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:56 24 4
gpt4 key购买 nike

为什么此表单未通过验证?它甚至没有调用 clean() 方法。

表单.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() 方法。我有另一种几乎相同的形式可以验证。当我在通过 request.POST 指令后执行 print dir(self.sample_form) 时,它指出 validation=unknown。为什么是这样?如何检查未验证的原因?

最佳答案

调用super()时需要传递*args**kwargs:

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

目前,不带任何*args**kwargs 调用__init__ 相当于调用data=None。表单未绑定(bind),因此永远不会有效。

关于python - 为什么这个 django 表单无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50468164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com