html response before saving object

27 views
Skip to first unread message

pyl...@gmail.com

unread,
Aug 4, 2014, 10:04:49 PM8/4/14
to django...@googlegroups.com
Hi Guys, 

I've update my site from django 1.3 to 1.5
The site works fine, except for a view, the template renders before the obj.save() in the view:

def cart(request):
    try:
        cart = Cart.objects.prefetch_related('cartitem_set__product__category').get(id=request.session['cart_id'])
    except (KeyError, Cart.DoesNotExist) as e:
        cart = Cart()
        cart.save()
        request.session['cart_id'] = cart.id

    if 'add' in request.GET:
        try:
            product = Product.objects.get(slug=request.GET['add'], active=True)
            cart_item = CartItem.objects.get(product=product, cart=cart)
        except CartItem.DoesNotExist:
            cart_item = CartItem(product=product, cart=cart)
            cart_item.save()
        except Product.DoesNotExist:
            pass

    response_args = {'cart': cart}
    return render_to_response('products/cart.html', response_args, context_instance=RequestContext(request))

I don't know why this happens
any help? something has changed? now the database save is async?

Collin Anderson

unread,
Aug 4, 2014, 10:19:39 PM8/4/14
to django...@googlegroups.com
database save is not async.

a few possibilities:
- does the product exist?
- is the cart_item really not created? (or is the cart the thing not being created?)
- is the prefetch_related pre-caching the related cart items, so in the template it doesn't see the new item? (hint: redirect to the same page to load the page again)
- are you using transactions?
- you could moving around some print statements, or my favorite: assert False, to see what code is actually getting run.

also, while you're upgrading (or after), you can now use simpler code for that last line:
return render(request, 'products/cart.html', response_args)

pyl...@gmail.com

unread,
Aug 4, 2014, 11:09:00 PM8/4/14
to django...@googlegroups.com
- does the product exist?
Yes, 

- is the cart_item really not created? (or is the cart the thing not being created?)
The cartItem is created, but it shown if I request again the url
1) request: /cart/?add=productslug
2) response: without the new item
3) request : /cart/
4) response: the item now is shown

- are you using transactions?
No 
 
- is the prefetch_related pre-caching the related cart items, so in the template it doesn't see the new item? (hint: redirect to the same page to load the page again)
I did not know that about prefetch_related, I have removed it and now working as expected.
 
also, while you're upgrading (or after), you can now use simpler code for that last line:
return render(request, 'products/cart.html', response_args)
Thanks :)

 
Reply all
Reply to author
Forward
0 new messages