在Django中获取Post值时的MultiValueDictKeyError

时间:2017-10-21 21:37:23

标签: python django

我正在尝试在Django中创建一个在线商店。在视图文件中,我循环遍历列表以查看产品ID是否与用户提交的内容相匹配。但是,我一直得到“MultiValueDictKeyError”。有没有办法解决这个问题?

查看文件

def index(request):
products = {
    "items" : items
}
return render(request, "app_main/index.html", products)

def buy(request):

for item in items:
     if item['id'] == int(request.POST['i_id']): ##<<--THIS IS WHERE IT 
                                                              ERRORS
     amount_charged = item['price'] * int(request.POST['quantity'])

try:
    request.session['total_charged']
except KeyError:
    request.session['total_charged'] = 0

try:
    request.session['total_items']
except KeyError:
    request.session['total_items'] = 0        

request.session['total_charged'] += amount_charged
request.session['total_items'] += int(request.POST['quantity'])
request.session['last_transaction'] = amount_charged

HTML文件

<table>
    <tr>
        <th>Item</th>
        <th>Price</th>
        <th>Actions</th>
    </tr>
    <tr>
    {% for i in items %}
    <td>{{ i.name }}</td>
    <td>{{ i.price }}</td>
    <td>
        <form action='/buy' method='post'>
        {% csrf_token %}
        <select name='quantity'>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        </select>
        <input type='hidden' name='{{ i.id }}'/>
        <input type='submit' value='Buy!' />
        </form>
    </td>
    </tr>
    {% endfor %}
    </table>

1 个答案:

答案 0 :(得分:2)

因为i_id未在模板中声明,所以应该更改;

<input type='hidden' name='{{ i.id }}'/>

<input type='hidden' name="i_id" value='{{ i.id }}'/>