Accessing session variable based on variable in for loop django template
I have some products listed which can be in a cart, this cart is stored in a session variable dictionary for which the key is the product id and the value is some information about the quantity and stuff. I want to add the option to view (on the products page) how many of that product are in your cart.
I know I can access session variables in a django template like this:
{{ request.session.cart.2323.quantity }}
Problem is, the key (2323 in this case) is a variable which depends on a for
loop:
{% for prod in products %}
<p>{{ request.session.cart[prod.name].quantity }}</p>
{% endfor %}
But implementing it like that unfortunately is not possible. Is there any way in which this would be possible or would I have to change the way my cart works?
You should implement a custom template filter like this to have the ability to use getattr.
from django import template
register = template.Library()
@register.simple_tag
def get_object_property_dinamically(your_object, first_property, second_property):
return getattr(getattr(your_object, first_property), second_property)
{% load get_object_property_dinamically %}
{% for prod in products %}
<p>{% multiple_args_tag request.session.cart prod.name 'quantity' %}</p>
{% endfor %}