django_django
django_django

Reputation: 21

Displaying the user's favorite products in Django

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 }}

Upvotes: 1

Views: 179

Answers (3)

ThaiBao
ThaiBao

Reputation: 113

{{ 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.all%}
{{product.name}}
{% endfor %}

instead of it.

Upvotes: 1

Ihor Pomaranskyy
Ihor Pomaranskyy

Reputation: 5611

Try something like this:

{% for product in data.products.all %}
{{ product.name }}
{% endfor %}

Upvotes: 1

NixonSparrow
NixonSparrow

Reputation: 6378

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 %}

Upvotes: 1

Related Questions