Django MultiValueDictKeyError

时间:2013-11-09 10:23:39

标签: django

这是错误:

MultiValueDictKeyError at /add_city/
"Key 'city_image' not found in <MultiValueDict: {}>"

这是POST信息:

Variable                 Value
country                  u'Bahrain'
csrfmiddlewaretoken      u'NyuznsyqteRfmgkUC9W0TpZeuuU99WMZ'
name                     u'vv'
city_image               u'Tuna_8.jpg'

这是观点:

class addCity(View):
    def get(self, request, *args, **kwargs):
        countries = Country.objects.all()
        return render_to_response('addCity.html', {'countries':countries}, RequestContext(request))

    def post(self, request, *args, **kwargs):
        name    = request.POST['name']
        country = Country.objects.get(name=request.POST['country'])
        image   = request.FILES['city_image']
        city    = City.objects.create(name=name, country=country, image= image)
        return HttpResponse("success")

这是我QueryDict时的print request.POST

<QueryDict: {u'country': [u'Bahrain'], u'csrfmiddlewaretoken': [u'NyuznsyqteRfmgkUC9W0TpZeuuU99WMZ'], u'name': [u'bb'], u'city_image': [u'user.png']}>

正如您所看到的,QueryDict中明确显示关键字“city_image”,那么为什么我收到错误消息“{1}}”未找到?

这是我的html文件。

key'city_image

这是追溯:

<form method="POST" enctype="multi-part/formdata">{% csrf_token %}
    <input type="text" name = "name" class="form-control" placeholder="City name" autofocus>
    <div class="control-group">
        <label for="country" class="control-label" style="margin:15px"></label>
        <div class="controls">
            <select name="country" id="country" class="form-control">
                <option value="">Select Country</option>
                {% for country in countries %}
                    <option value="{{country}}">{{country}}</option>
                {% endfor %}
            </select>
        </div>
    </div>
    <input name ="city_image" type="file" style="margin:15px">
    <input button class="btn btn-lg btn-primary btn-block" id = "create_city_button" type="submit" value = "Create City">
</form>

1 个答案:

答案 0 :(得分:9)

您没有粘贴回溯,但我猜KeyError来自request.FILES,而不是request.POST。这可能是因为您没有在表单元素中包含enctype="multipart/form-data"