I had a question about django-templates. I was wondering about if we can add a filter in django template. I want to know if the product is in wishlist or no while rendering it. So, how can we know if it's in the wishlist or no? views.py
def store(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
categories = Category.objects.all()
products = Product.objects.all()
if request.user.is_authenticated:
user=request.user
wishedProducts = Wishlist.objects.filter(user=user)
else:
wishedProducts = {}
"""popularnye = Product.objects.filter(popularnye=True)"""
context = {'products':products, 'cartItems':cartItems, 'order':order, 'items':items, 'categories':categories,'wishedProducts':wishedProducts}
return render(request, 'store/store.html', context)
models.py
class Wishlist(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, verbose_name="Название товара",null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
unique_together = (
('user', 'product'),
)
verbose_name = 'Избранные'
verbose_name_plural = "Избранные"
def __str__(self):
return str(self.product)
template
{% for product in products %}
<div >
<div >
<div >
<div >
<p style="margin-top:-10px;margin-bottom:-10px" >Код: 51265</p>
{% if product in wishedProducts.product %}
<i style="color: red" data-product="{{product.id}}" data-action="add"></i>
{% else %}
<i data-product="{{product.id}}" data-action="add"></i>
{% endif %}
<i style="margin-right:5px;"></i>
........
CodePudding user response:
I solved this problem by creating another list with products of wishlist. views.py
if request.user.is_authenticated:
user=request.user
wishedProducts = Wishlist.objects.filter(user=user)
wishedProductsList = []
for i in wishedProducts:
wishedProductsList.append(i.product)
count = Wishlist.objects.filter(user=user).count()
else:
wishedProducts = {}
wishedProductsList={}
template
{% for product in products %}
<div >
<div >
<div >
<div >
<p style="margin-top:-10px;margin-bottom:-10px" >Код: 51265</p>
{% if product in wishedProductsList %}
<i style="color: red" data-product="{{product.id}}" data-action="add"></i>
{% else %}
<i data-product="{{product.id}}" data-action="add"></i>
{% endif %}
<i style="margin-right:5px;"></i>
CodePudding user response:
You can obtain the products with:
def store(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
categories = Category.objects.all()
products = Product.objects.all()
if request.user.is_authenticated:
wishedProducts = Product.objects.filter(wishlist__user=request.user)
else:
wishedProducts = Product.objects.none()
context = {'products':products, 'cartItems':cartItems, 'order':order, 'items':items, 'categories':categories,'wishedProducts':wishedProducts}
return render(request, 'store/store.html', context)
This will fetch all the Product
s in the wishlist in a single query, and thus avoid an N 1 problem.