gpt4 book ai didi

Django forms.FileField(required=True) 如果为空则通过验证

转载 作者:行者123 更新时间:2023-12-02 02:08:09 25 4
gpt4 key购买 nike

我有一个带有必需文件字段的 Django 表单(不是 ModelForm)。根据the FileField documentation ,FileField 的验证应该验证非空文件数据是否已绑定(bind)到表单,但我没有看到这种行为。相反,我可以在没有文件的情况下提交表单,并且表单通过验证。预期的行为是验证失败。

当在表单中指定文件时,事情会按预期工作。

我的表单看起来像这样:

class BucketUploadForm(forms.Form):
file = forms.FileField(required=True) # required=True is the default, but I'm being explicit

def clean(self):
upload_to = '/some/path'
upload_to += self.cleaned_data['file'].name # this is raising a KeyError

我的观点看起来像这样:

def bucket_upload(request):
if request.method == 'POST':
form = BucketUploadForm(request.POST, request.FILES)
if form.is_valid(): # this is raising the aforementioned KeyError when no file is submitted
do_stuff()
return HttpResponseRedirect(some_url)
else:
form = BucketUploadForm(initial=request.GET)
return render_to_response('handin/bucket_upload.html', {'form': form}, context_instance=RequestContext(request))

我的模板看起来像这样:

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Upload" />
</form>

回溯看起来像这样:

Django Version: 1.3.1
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'hgrepo',
'sshkey',
'handin',
'accounts']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/views/decorators/http.py" in inner
45. return func(request, *args, **kwargs)
File "/home/sduckwo/projects/webhandin/webhandin/handin/views.py" in bucket_upload
461. if form.is_valid():
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in full_clean
268. self._clean_form()
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in _clean_form
296. self.cleaned_data = self.clean()
File "/home/sduckwo/projects/webhandin/webhandin/handin/forms.py" in clean
116. upload_to += self.cleaned_data['file'].name

Exception Type: KeyError at /courses/a/b/assignments/c/sduckwo/upload
Exception Value: 'file'

更新

从 BucketUploadForm 中删除 clean 方法会导致 FileField 的验证按预期失败。但是,我需要 clean 方法来进行其他检查,因此无法永久删除它。

我还发现,通过将 clean 方法修改为如下所示:

class BucketUploadForm(forms.Form):
file = forms.FileField(required=True) # required=True is the default, but I'm being explicit

def clean(self):
if 'file' not in self.cleaned_data:
raise ValidationError('No file or empty file given')
upload_to = '/some/path'
upload_to += self.cleaned_data['file'].name # this is raising a KeyError

然后验证按预期失败,但我收到两条错误消息:

  1. “没有给出文件或空文件”,由 BucketUploadForm.clean() 引发
  2. “此字段是必需的”,由 FileField.clean() 引发,这就是我最初想要的。

这告诉我 FileField.clean() 正在引发 ValidationError,但该异常会以某种方式被忽略,除非 BucketUploadForm.clean() 不存在或也引发 ValidationError。

所以现在我可能更接近我的最终目标,但仍然很困惑。

最佳答案

我想我以前见过这个。从轶事经验来看,如果缺少字段,Django 似乎不会停止验证(例如,即使缺少必填字段,它也会调用 clean() )。它表示由于未在 clean_data 中包含字段名称而缺少必填字段。

斯科特指出它是 documented here :

For any field, if the Field.clean() method raises a ValidationError, any field-specific cleaning method is not called. However, the cleaning methods for all remaining fields are still executed.

因此,我认为解决方案只是通过检查“file”键是否在cleaned_data中来防御性地对clean()方法进行编程,如果不是,则按原样返回cleaned_data。 Django 已经知道缺少必需的字段,因此 is_valid() 将失败并且不会造成任何损害。

def clean(self):
upload_to = '/some/path'
if not 'file' in self.cleaned_data:
return self.cleaned_data
upload_to += self.cleaned_data['file'].name

关于Django forms.FileField(required=True) 如果为空则通过验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17596343/

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