When I try add the product to wishlist it gives me above error, It still saves the object to model

def plus_wishlist(reques):
    if request.method == "GET":
        prod_id = request.GET.get('prod_id')
        product = Product.objects.get(id=prod_id)
        ruser = request.user
        wishlist = Wishlist.objects.create(user=ruser, product=product)
        wishlist.save()
        return JsonResponse({'message': 'Added to Wishlist.'})

Also when i try to use

 ruser=request.user.id

ValueError: Cannot assign "1": "Wishlist.user" must be a "User" instance.

class Wishlist(models.Model):
        user=models.ForeignKey(User,on_delete=models.CASCADE)
        product=models.ForeignKey(Product,on_delete=models.CASCADE)

Issue is Solved!!

ruser = get_object_or_404(User,id=request.user.id)

I dont know if there was login error or what, after getting same error I cleared localhost url and it took me to login page after login there was no issue

2

There are 2 best solutions below

9
willeM_ Van Onsem On

Limit views to a view to authenticated users with the @login_required decorator [Django-doc]:

from django.contrib.auth.decorators import login_required


@login_required
def plus_wishlist(reques):
    if request.method == 'GET':
        prod_id = request.GET.get('prod_id')
        product = Product.objects.get(id=prod_id)
        ruser = request.user
        wishlist = Wishlist.objects.create(user=ruser, product=product)
        wishlist.save()
        return JsonResponse({'message': 'Added to Wishlist.'})

We can also boost efficiency with:

from django.contrib.auth.decorators import login_required


@login_required
def plus_wishlist(reques):
    if request.method == 'GET':
        prod_id = request.GET.get('prod_id')
        wishlist = Wishlist.objects.create(
            user_id=request.user.id,
            product_id=prod_id
        )
        return JsonResponse({'message': 'Added to Wishlist.'})

That being said, you can not add an item to a Wishlist with a GET request: GET requests should have no side-effects. Adding something to a Wishlist thus should be done with a POST request.

0
Luis Miguel Sotamba On

If the user is not authenticated, then Django will return Anonymous user when you got the user using request.user. That instance doesn't have an id attribute. You should be sure the user is authenticated before of creating products. Now, the following issue: It still saves the object to model, I think that your Wishlist model allows setting a null value to the user property.