Pregunta

I've got a template 'cart_summary.html' which renders fine when I it appears as an include on another template {% include 'cart/cart_summary.html' %}.

However when I render it directly from a view function (called by ajax), my context variables do not render as expected:

# views.py
def add_to_cart(request):
    ...
    cart = request.session['cart']
    ...
    return render_to_response('cart/cart_summary.html', {'cart': cart})

my cart_summary.html template -

<a src="{% url cart-page pk=cart.pk %}">
    <span> CART ({{ cart.count }}) &pound;{{ cart.get_total }} </span>
    <img id="cart_icon" src="{{ STATIC_URL }}images/cart_icon.tiff">
</a>

And this is kind of stuff I'm getting returned to the browser -

<span> CART (&lt;bound method ManyRelatedManager.count of &lt;django.db.models.fields.related.ManyRelatedManager object at 0x106bfa150&gt;&gt;) &pound; </span>
<img id="cart_icon" src="images/cart_icon.tiff">

What do I need to do to get the properly rendered string?

¿Fue útil?

Solución

Your method is returning a method instead of a value.

Probably it is returning queryset.count instead of queryset.count()

Otros consejos

After several hours of debugging some spectacularly poor code (my code), I found the error. It was actually in the Cart model. The count function was written so that it was returning a method rather than the output of a method

def count(self):
    return self.items.count

should have been

def count(self):
    self.items.count()

I was thrown off the scent by the fact it was being converted to html safe code, (that and all the other errors in my code).

Try this...

from django import template
return render_to_response('cart/cart_summary.html', {'cart': cart}, context_instance = template.RequestContent(request))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top