2

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?

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88

3 Answers3

7

Your method is returning a method instead of a value.

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

jpic
  • 32,891
  • 5
  • 112
  • 113
2

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).

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88
0

Try this...

from django import template
return render_to_response('cart/cart_summary.html', {'cart': cart}, context_instance = template.RequestContent(request))
Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
  • Thanks Raunak. Adding the context instance doesn't change the output. It's still not processing my context variables. – Aidan Ewen Nov 23 '12 at 06:39