D
D
Dennis2016-06-23 20:20:37
Django
Dennis, 2016-06-23 20:20:37

Django - cart implementation?

models.py:

class Product(models.Model):
    sku = models.CharField(max_length=50)
    price = models.DecimalField(decimal_places=2, max_digits=10)

class CartItem(models.Model):
    cart = models.ForeignKey('Cart', null=True, blank=True)
    item = models.ForeignKey(Product)
    quantity = models.PositiveIntegerField(default=1)
    item_total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

class Cart(models.Model):
    total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)

forms.py:
class ProductsForm(forms.Form):
    products = forms.ModelChoiceField(label=u'Products', queryset=Product.objects.all())

views.py:
class CartView(FormView):
    template_name = 'cart.html'
    form_class = ProductsForm

    def get(self, request, *args, **kwargs):
        cart_id = self.request.session.get("cart_id")
        if cart_id == None:
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id
        cart = Cart.objects.get(id=cart_id)
        if not request.is_ajax():
            form = self.get_form()
            return self.render_to_response(self.get_context_data(form=form, cart=cart))

        if request.is_ajax():
            item_id = request.GET.get("product")
            item_instance = get_object_or_404(Product, id=item_id)
            cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance)
            if not created:
                cart_item.quantity += 1
                cart_item.save()

            data = {}
            return JsonResponse(data)

cart.html:
{% block jquery %}

    $('.btn-default').click(function(e){
        var product = $('select option:selected').val();
        var data = {product: product};
        $.ajax({
            type: 'GET',
            url:'{% url "cart" %}',
            data: data
        });
    });

{% endblock %}

{% block content %}

<div class="container">
    <div class="row products">
        <div class="col-md-4 col-md-offset-4">
            <form action="." method="GET">{% csrf_token %}
                {{ form|crispy }}

                <input class="btn btn-default" type="button" value="Add to cart" />
            </form>
        </div>
    </div>
<div class='row cart'>
        <div class='col-md-8 col-md-offset-2'>

            <h3>Your cart</h3>

            <table class='table'>
                <thead>
                    <th>Item</th>
                    <th>Price</th>
                    <th>Qty</th>
                    <th>Item Total</th>
                </thead>

                {% for item in cart.cartitem_set.all %}
                    <tr>
                        <td>{{ item.item.sku }}</td>
                        <td>{{ item.item.price }}</td>
                        <td>{{ item.quantity }}</td>
                        <td>{{ item.item_total_price }}</td>
                    </tr>
                {% endfor %}

                <tr id="checkout">
                    <td colspan='4' class='text-right'>Total: {{cart.total}}</td>
                </tr>
                <tr id="checkout">
                    <td colspan='4' class='text-right'><a class='btn btn-warning' href="{% url 'checkout' %}">Checkout</a></td>
                </tr>

            </table>

        </div>
    </div>
</div>

{% endblock %}

Everything happens on one page. There is a SELECT form with products. I select a product and press a button. In this case, the product should appear in the basket, i.e. in the table below the form.
But the product does not appear in the table immediately when the button is clicked, it only appears after the page is refreshed. How to fix it?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-06-23
@denismatveyev7

But the product does not appear in the table immediately when the button is clicked, it only appears after the page is refreshed. How to fix it?
Well, js, no one said that it should redraw the table
$('.btn-default').click(function(e){
        var product = $('select option:selected').val();
        var data = {product: product};
        $.ajax({
            type: 'GET',
            url:'{% url "cart" %}',
            data: data
        })
.success(function (data) {
console.log(data);
// вот тут организуй рендеринг новой корзинки в тело хтмл
$('.table tr').remove();
html = '';
for(var i;i<data.length; i++) {
html += '<tr><td>'+data.sku+ '</td></tr>'
}
$( html ).insertAfter( ".table thead" );
})

;
    });

ps: code may not work :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question