Ben Sargent Ben Sargent - 11 months ago 35
Python Question

I am trying to print a cart with prices in Django

When I pass the context, the other end doesn't seem to be able to use it, to make it simpler and give an example I will try passing all my products and simply make a list of all the product id's, it doesn't work, all I get is a blank page when I visit the page.

def cart(request):
items = [1,2,3,4]
template = loader.get_template("Cafe/cart.html")
ip = get_client_ip(request)
order = current_order.objects.order_by('id')
products = product.objects.order_by('id')
context = {
'order': order,
'products': products,
'items': items
return HttpResponse(template.render(request))


{% load static %}
{% load app_filters %}
<link rel="stylesheet" type="text/css" href="{% static 'Cafe/stylesheet.css' %}" />
{% for product in products %}
{% endfor %}

class product(models.Model):
categories = (
('HD', 'Hot Drink'),
('CD', 'Cold Drink'),
('Br', 'Breakfast'),
('Sa', 'Sandwich'),
('Ex', 'Extras'),
('Sp', 'Specials'),
product_name = models.CharField(max_length=100)
category = models.CharField(max_length=2, choices=categories, default=categories[0][0])
price = models.FloatField()

I don't see a reason why this should not work as the same concept works on all other pages I have made.

Answer Source

Instead of rendering your template like this:

return HttpResponse(template.render(request))

You could do:

context = {'order': order, 'products': products, 'items':items}
return render(request, "cafe/cart.html", context)

Right now your context variable isn't being used when rendering anything, so you can't access it in the template. Using render like this and supplying a context dictionary will give you access to all of the items within the dict like you'd expect.