MultiValueDictKeyError Django 1.8

时间:2017-11-30 15:17:50

标签: django python-2.7

我正在尝试使用forms.py导入文件。这段代码与我在另一个模型中使用的代码相同,但它确实有效,但这次它给了我这个错误:

MultiValueDictKeyError at /importraw 
Exception Value: "u'rawname'"

以下是您需要了解的代码片段:

Views.py

def importraw(request):
    form = UploadRaw(request.POST, request.FILES)
    if form.is_valid():
        raw = Raw(title=request.POST['rawname'], file='raw_files/' + request.POST['file'])
        raw.save()
        handle_uploaded_raw(request.FILES["file"], request.POST["name"])
        raw.save()
    return redirect('/importations')

Urls.py:

url(r'^importraw$', views.importraw),

Forms.py:

class UploadRaw(forms.Form):
    class Meta:
        name = forms.CharField(max_length=120)
        file = forms.FileField()

Models.py:

class Raw(models.Model):
    title = models.CharField(max_length=200)
    file = models.FileField(upload_to='raw_files')
    uploaded_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.name

的index.html

<!--IMPORT-->
    <div class="col-md-12">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">Importer un fichier brut</h3>
                  </div>
                  <div class="panel-body">
                <form class="form-horizontal" action="/importraw", method="post">
                {% csrf_token %}
                  <fieldset>
                    <div class="form-group">
                      <label for="name" class="col-lg-4 control-label">Structure</label>
                        <div class="col-lg-6">
                            <select name="id" id="id" class="struct form-control">
                                         {% for structure in structures %}
                                             <option value="{{ structure.name }}">{{ structure }}</option>
                                         {% endfor %}
                                     </select>
                            </div>
                    </div>
                    <div class="form-group">
                        <label for="file" class="col-lg-4 control-label">Nom du fichier brut</label>
                        <div class="col-lg-6">
                          <input type="text" name="rawname" id="rawname" class="form-control">
                        </div>
                      </div>
                    <div class="form-group">
                        <label for="file" class="col-lg-5 control-label">Fichier brut</label>
                        <div class="col-lg-6">
                          <input type="file" name="file" id="file">
                        </div>
                      </div>
                    <div class="form-group">
                      <div class="col-lg-10 col-lg-offset-2" align="center">
                        <button type="submit" value="Create" class="btn btn-primary">Importer</button>
                      </div>
                    </div>
                  </fieldset>
                </form>
                </div>
            </div>
        </div>

    <!--END-IMPORT-->

要详细了解我遇到的确切错误,请查看以下追溯:

**Environment:
Request Method: POST
Request URL: http://localhost:8000/importraw
Django Version: 1.8
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'backoffice']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/kaiss/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kaiss/Desktop/projet2/backoffice/views.py" in importraw
  232.         raw = Raw(title=request.POST['rawname'], file='raw_files/' + request.POST['file'])
File "/home/kaiss/.local/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__
  322.             raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /importraw
Exception Value: "u'rawname'"**

我正在使用Python 2.7.13和Django 1.8。

提前非常感谢你!

1 个答案:

答案 0 :(得分:1)

您收到错误,因为rawname不在request.POST中。在您的情况下,表单是有效的,因此最好从表单“clean_data”而不是request.POST中获取值。

if form.is_valid():
    raw = Raw(title=form.cleaned_data['title'], file='raw_files/' + request.POST['file'])

如果您直接从request.POST访问数据,您的代码应该处理这种可能性,要么检查密钥是否存在,

if 'rawname' in request.POST:
    rawname = request.POST['rawname']

或使用get()方法并指定默认值。

rawname = request.POST.get('rawname', '')

最后,您的表单没有意义。常规表单没有Meta类,字段应该在类中定义,而不是在Meta类中定义。

一个简单的model form可能看起来像:

class UploadRaw(forms.ModelForm):
    class Meta:
        fields = ('title', 'file')

然后,simplify your template首先使用{{ form }}。一旦您的视图正常工作,您可以直到视图正常工作。然后,如果您愿意,可以手动render the fields