试图制作一个处理多个文件上传并将其存储到标准位置的应用程序,但我遇到了一个问题。提交表单时,django在/pdfchecker/返回"MultiValueDictKeyError
"'docfile'"
forms.py
from django import forms
class UploadPdf(forms.Form):
docfile = forms.FileField(label='Browse')
class UploadPdfUrl(forms.Form):
docurl = forms.URLField(label='Address')
型号.py
from django.db import models
class handle_UploadPdf(models.Model):
docfile = models.FileField(upload_to='.')
views.py
def上传(请求):
UploadPdfFormSet = formset_factory(UploadPdf, max_num=10,)
if request.method == 'POST':
formsetFile = UploadPdfFormSet(request.POST, request.FILES)
if formsetFile.is_valid():
newdoc = handle_UploadPdf(docfile = request.FILES['docfile'])
newdoc.save()
return HttpResponse('yey')
else:
formsetFile = UploadPdfFormSet()
formURL = UploadPdfUrl
return render(request, 'pdfchecker/index.html', {
'formsetFile': formsetFile, 'formURL': formURL,
})
page_visits = int(request.COOKIES.get('page_visits', '0'))
if request.COOKIES.has_key('last_visit'):
last_visit = request.COOKIES['last_visit']
last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S")
if (datetime.now() - last_visit_time).seconds > 5:
response.set_cookie('page_visits', visits+1)
response.set_cookie('last_visit', datetime.now())
else:
response.set_cookie('last_visit', datetime.now())
return response
HTML模板:
<div class="f_unify">
<form class="simpleform" action="" method="post" enctype="multipart/form-data">
{{ formsetFile.management_form }}
{% for form in formsetFile.forms %}
<fieldset class="mainfieldset">
<legend class="outer">
<span class="legendtext">Check by URI</span>
</legend>
<div class="singlerow">
{% csrf_token %}
{{ formURL.as_table }}
<input type="submit" value="Check" />
</div>
<span class="description">(<cite>http://www.egovmon.no/test.pdf</cite>)</span>
</fieldset>
{% endfor %}
</form>
<form class="simpleform" action="." method="post" enctype="multipart/form-data">
{{ formsetFile.management_form }}
{% for form in formsetFile.forms %}
<fieldset class="mainfieldset">
<legend class="outer">
<span class="legendtext">Check by File Upload</span>
</legend>
<div class="singlerow">
<div class="table">
<input type="submit" value="Check" />
<table class='no_error'>
{% csrf_token %}
{{ formsetFile.as_p }}
</table>
</div>
</div>
</fieldset>
{% endfor %}
<script>
var maxRows = 10;
var i = 1;
$('#add_more').click(function() {
if(i < maxRows) {
cloneMore('div.table:last', 'service' + i++);
}
else {
alert('You can only upload 10 files per instance')
}
})
</script>
</form>
</div>
设置.py:
"""
Django settings for testproject project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0o0g&$q4jeg%d#+5gu^b2x0jclifrul-3^q0e9(x_vwqdz3+x@'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pdfchecker',
'authentication',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'testproject.urls'
WSGI_APPLICATION = 'testproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS =(
os.path.join(os.path.dirname(BASE_DIR), "static"),
)
错误:
Error:
MultiValueDictKeyError at /pdfchecker/
"'docfile'"
Request Method: POST
Request URL: http://tt5.s.tingtun.no:7842/pdfchecker/
Django Version: 1.6.1
Exception Type: MultiValueDictKeyError
Exception Value:
"'docfile'"
Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py in __getitem__, line 301
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/student/django/1utkast/src',
'/usr/local/lib/python2.7/dist-packages/TingtunUtils-0.1-py2.7.egg',
'/usr/local/lib/python2.7/dist-packages/requests-2.0.1-py2.7.egg',
'/usr/local/lib/python2.7/dist-packages/setuptools-2.0.1-py2.7.egg',
'/usr/local/lib/python2.7/dist-packages/pip-1.4.1-py2.7.egg',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/pymodules/python2.7']
Server time: Mon, 28 Apr 2014 14:10:07 +0000
追溯:
Traceback Switch to copy-and-paste view
/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
...
▶ Local vars
/home/student/django/1utkast/src/pdfchecker/views.py in upload
newdoc = handle_UploadPdf(docfile = request.FILES['docfile'])
...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py in __getitem__
raise MultiValueDictKeyError(repr(key))
...
▶ Local vars
在views.py中,
request.FILES['docfile']
引发MultiValueDictKeyError,其中
if request.method == 'POST':
formsetFile = UploadPdfFormSet(request.POST, request.FILES)
if formsetFile.is_valid():
newdoc = handle_UploadPdf(docfile = request.FILES['docfile'])
newdoc.save()
return HttpResponse('yey')
此代码段不检查请求的文件是否包含文件"docfile",因此它给出了多值dictkeyerror。因此,如果您检查"docfile"是否在请求中。FILES之前,它解决了错误。
if formsetFile.is_valid() and 'docfile' in request.FILES:
newdoc = handle_UploadPdf(docfile = request.FILES['docfile'])
newdoc.save()
因为请求。如果FILES['docfile']不在请求中,则不会编译它。文件