Ricky Rathbone
Ricky Rathbone

Reputation: 45

MultiValueDictKeyError when getting a Post Value in Django

I'm trying to create an online store in Django. In the views file, I'm looping through the list to see if the product id matches what the user submitted. However, I keep getting "MultiValueDictKeyError". Is there a way I can fix this?

VIEWS FILE

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 FILE

<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>

Upvotes: 1

Views: 590

Answers (1)

binpy
binpy

Reputation: 4194

It because i_id doesn't declare in the template, you should change;

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

to;

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

Upvotes: 2

Related Questions