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?

有帮助吗?

解决方案

Your method is returning a method instead of a value.

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

其他提示

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))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top