Reputation: 912
I am working on a Django E-commerce Project, and I have been following a tutorial and afterwards I decided to redo it on my own without the tutorial but I am stuck in a small issue which I don't understand the logic behind it.
When a user adds an Item to Cart I want it to reflect on the no. of items that are showing on the navbar cart icon, but I am getting Invalid filter: 'cart_item_count'
Here is my Item model.py
class Item(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(blank=False, upload_to=upload_design_to)
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
variation = models.ManyToManyField(Variation)
The application name is store
, so here is what I have been done in the tutorial
Added a new folder in the app with the name of templatetags
and inside the template tags folder created file called cart_template_tags
and here is what is inside it:
from django import template
from store.models import Order
register = template.Library()
@register.filter
def cart_item_count(user):
if user.is_authenticated:
qs = Order.objects.filter(user=user, ordered=False)
if qs.exists():
return qs[0].items.count()
return 0
My question is how do I fix this error and I want to understand behind the logic of having cart_item_count
as a filter?
Is there an easier way to do it?
Thank you
Upvotes: 0
Views: 347
Reputation: 3248
According to django doc about custom template tags, you need to
{% load cart_template_tags %}
in your template.Upvotes: 1