Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django e-commerce part44 Update Cart Item Quantity In Cart

カートの数量をカートの中で更新できるようにする。

carts/view.htmlを修正

{% extends "base.html" %}

{% block content %}

<table class='table'>

{% for item in object.cartitem_set.all %}

<tr>
<form action="." method="GET">
    <td>{{ item.item.get_title }}</td>
    # 以下のパラメータは、hiddenにして表示はしないが、requestには渡すようにする。
    <input type='hidden' name='item' value='{{ item.item.id }}'/> 
    # item=CartItem()のため、Cartitem.quantity に、qtyの数値が代入される。
    <td><input type='number' name='qty' value='{{ item.quantity }}'/></td>
    <td>{{ item.line_total }}</td>
    <td class='text-right'><a href='{{ item.remove }}'>削除</a>
    <input type='submit' class='btn btn-link' value='更新する'/></td>
</tr>
</form>
{% endfor %}

</table>

{% endblock %}

さらに修正して以下のようにする。 修正点は、class='item-qty'、class='btn-update'、style='diplay:none;'の追加

<form action="." method="GET">
    <td>{{ item.item.get_title }}</td>
    <input type='hidden' name='item' value='{{ item.item.id }}'/>
    <td><input type='number' class='item-qty' name='qty' value='{{ item.quantity }}'/>
    <input type='submit' class='btn-update btn btn-link' value='更新する' style='diplay:none;'/></td>
    <td>{{ item.line_total }}</td>
    <td class='text-right'><a href='{{ item.remove }}'>削除</a></td>
</tr>
</form>

views.html にjQueryを入れていく

jqueryで、数量変更の時に、更新ボタンが出てくるようにする。

<script>
{% block jquery %}
$(".item-qty").change(function(){
    $(this).next(".btn-update").fadeIn();
});
{% endblock %}

</script>