Reputation: 1215
I'm trying to read a cookie and pass the data into the template but it returns a string /cart
on the template.
view.py
def cart(request):
# exception no cookie named 'cart'
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
context = {
'data': [],
'cart': cart,
}
for item in cart:
product_detail = ProductImage.objects.select_related(
'product'
).filter(product=item[0], place='Main Product Image')
context['data'].append(product_detail)
return render(request, 'store/cart.html', context)
I've checked whether the cart
variable contains data and it does contain a dictionary. Following is the context
variable,
{'data': [<QuerySet [<ProductImage: Product 1-22>]>], 'cart': {'1': {'unit_price': '980.00', 'quantity': 3}}}
when I tried to print the cart in the template using {{ cart }}
it returns /cart
but the data
key contains all the data and can be displayed in the template.
template
{{ cart }} <!-- for testing -->
{% for item in data %}
{% if forloop.counter|divisibleby:2 %}
<div class="row border-bottom pb-3 pt-1 cart-item">
{% else %}
<div class="row border-bottom pb-3 pt-1 cart-item" style="background-color: #F8F8F8">
{% endif %}
<div class="col-sm-1 d-md-flex justify-content-center align-items-center remove-btn">
<button type="button" class="btn bg-transparent"
data-action="delete" data-product="{{ item.0.product.id }}_{{ item.0.product.get_sale_price|floatformat:2 }}">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
<div class="col-sm">
<img class="img-fluid img-thumbnail" src="{{ item.0.image.url }}" alt="" />
</div>
<div class="col-sm">
<a href="product/{{ item.0.product.id }}" class="cart-product-link">
<h5> {{ item.0.product.name }}</h5>
<p class="module fades">
{{ item.0.product.desc }}
</p>
</a>
</div>
<!-- quantity -->
<div class="col col-sm input-group my-auto text-center">
<div class="quantity ml-5">
<input type="number" class="update-quantity" data-action="q_add" min="1" max="20" step="1"
value="{{ cart|get_quantity:item.0.product.id }}" style="width: 50px"
data-product="{{ item.0.product.id }}_{{ item.0.product.get_sale_price|floatformat:2 }}">
</div>
</div>
<!-- cost -->
<div class="col col-sm mt-lg-5 text-center cost-container">
<span class="cost">{{ cart|get_cost:item.0.product.id }}</span>
</div>
</div>
{% endfor %}
So hoping to know what's going on here thanks in advance.
Update(wierd scenario)
The same thing happened again in a different file and I tried to do the solution bellow mentioned. Unfortunately, it didn't work. After hours of trying, I decided to rename the key of the dict {'cart': cart,...}
to {'crt':cart}
and it worked.
Upvotes: 0
Views: 127
Reputation: 2019
If you want to pass a context dict variable in the template. All you need to do is :
return render(request, 'store/cart.html', {'context' : context})
By this we are passing the context to html template. And the you can retrieve the context data by :
{{context.cart}}
Upvotes: 1