I’m trying to load data from my django views into my django templates without refreshing the page with jquery. I have a cart function in my views that’s returning all the items in a users cart. I would like to display all the items on the click of a button in a django template with jQuery. I can’t seem to figure out what I’m doing wrong.
Here is my views:
def cart(request):
template = loader.get_template("main/cart.html")
if request.user.is_authenticated:
email = request.user.email
usercartitems = request.user.cart_item_set.all()
cartitems = []
store = ""
totalprice = 0
numberofitemsincart = len(cartitems)
for item in usercartitems:
quantity = item.product_quantity
store_id = item.store_id
product_id = item.product_id
storedetail = Store_detail.objects.get(pk = store_id)
product = Product.objects.get(pk = product_id)
item = {"quantity":quantity, "product":product}
cartitems.extend([item])
store = storedetail
numberofitemsincart = len(cartitems)
product = Product.objects.get(pk = product_id)
totalproductprice = product.price * int(quantity)
totalprice += totalproductprice
context={
'store':store,
'email':email,
'cartitems':cartitems,
'numberofitemsincart':numberofitemsincart,
'totalprice':totalprice,
}
return HttpResponse(template.render(context,request))
elif request.user.is_authenticated is False:
if request.session.get('cart'):
allitems = request.session['cart']
cartitems = []
totalprice = 0
for item in allitems.values():
store_id = item['store_id']
quantity = item['quantity']
product_id = item['product_id']
product = Product.objects.get(pk = product_id)
store = Store_detail.objects.get(pk = store_id)
totalproductprice = product.price * int(quantity)
totalprice += totalproductprice
cartdict = {'store':store,'product':product,'quantity':quantity,}
cartitems.append(cartdict)
context = {
'cartitems':cartitems,
'totalprice':totalprice,
}
else:
context = {}
return HttpResponse(template.render(context,request))
else:
return HttpResponse(template.render(context,request))
Here is my jQuery:
$('#cart').click(
function(e){
e.preventDefault();
$.ajax({
type:"GET",
dataType: "json",
url:"{% url 'main:cart' %}",
data: {
'cartitems': cartitems
}
success:function(data){
console.log(data);
}
});
});
2
Answers
Instead of using
HttpResponse(template.render(context,request))
, you should use therender
shortcut:It looks like you want to deal with
json
data as a result to your request. If you only have one item to update in your html page, to me it’s not necessary to render the whole thing, andjquery
is one way to go.I also think it is too complicated to deal with context stuff for that. Here is an example to return your user a
json
response you can then work with in yourjquery
piece of code:You will then be able to work with the data you just fetched!