Displaying the user's favorite products in Django
When I want to display the user's favorite products, the query result does not display anything and returns me None. Actually, I want to show the user which products he has added to his favorite list
My model, view and address Url as follows
my model:
class UserWishlist(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, related_name='user_favourite')
products = models.ManyToManyField(Product, related_name='product_favourite', blank=True, )
my url :
path('wish/', views.wish, name='wish'),
my view:
def wish(request):
data = UserWishlist.objects.get(user_id=request.user.id)
return render(request, 'home/test.html', {'data': data})
my template :
{{ data.products.name }}
CodePudding user response:
Your products
is a ManyToManyField
, which returns QuerySet
, so you have to treat it as it is a list. You should render it more likely like this (assuming, that data
is UserWishlist
object):
{% for product in data.products.all %}
{{ product.name }}
{% endfor %}
CodePudding user response:
Try something like this:
{% for product in data.products.all %}
{{ product.name }}
{% endfor %}
CodePudding user response:
{{ data.products.name }} return a list but you didn't use a loop to list it out, right? You should use
{% for product in data.products%}
{{product.name}}
{% endfor %}
instead of it.