local variable 'user' referenced before assignment error in django function

Question:

I have this function in django that adds a new item to the wishlist, the function is doing what it should do but when I add a new user that was not registered, when adding an item to the wish list it returns this error, but when i refresh the page the error no longer exist.

I think the problem is that when a new user registers, he still does not have the database created in the wishlist model, so the try: condition fails because the user does not yet exist in the model, passing the except: condition where the user database is created, but I have to manually refresh the page so that the page no longer shows me the error.

How can I fix this so that the page no longer shows me this error?

def add_or_remove(request, listing_id):
    if request.method == "POST":
        if (request.POST["action"]) == "add":
            try:
                user = Wishlist.objects.get(user=request.user)
                listing = Listing.objects.get(pk=listing_id)
                user.item.add(listing)
            except:
                create = Wishlist(
                user=request.user,
                )
                create.save()
                user.item.add(listing)
                messages.success(request, 'you added to Wishlist')

        elif (request.POST["action"]) == "remove":
            user = Wishlist.objects.get(user=request.user)
            item = user.item.get(id=listing_id)
            user.item.remove(item)

            messages.success(request, 'you removed from Wishlist')

        return redirect(reverse("listing", args=[listing_id]))
Asked By: kroma235

||

Answers:

Django ORM’s ‘get’ function may raise an exception when the requested object is not in the database, you can assure the existence of the ‘user’ object before going to the next line with a simple logic like this (I’ve renamed it to ‘wishlist’ according to the model name):

try:
   wishlist = Wishlist.objects.get(user=request.user)
except Wishlist.DoesNotExist:
   wishlist = Wishtlist(user=request.user)
   wishlist.save()

Or you can use Django’s built-in get_or_create() function that does the same thing out-of-the-box.

wishlist = Wishlist.objects.get_or_create(user=request.user)

Please note that your naming conventions may be a little misleading. And also, you need the same logic for the ‘listing’ object after ‘user’.

Answered By: abexamir

As the error suggests, simply assign it as empty string at just starting of POST method, so:

def add_or_remove(request, listing_id):
    if request.method == "POST":
        user=""
        if (request.POST["action"]) == "add":
            try:
                user = Wishlist.objects.get(user=request.user)
                listing = Listing.objects.get(pk=listing_id)
                user.item.add(listing)
            except:
                create = Wishlist(
                user=request.user,
                )
                create.save()
                user.item.add(listing)
                messages.success(request, 'you added to Wishlist')

        elif (request.POST["action"]) == "remove":
            user = Wishlist.objects.get(user=request.user)
            item = user.item.get(id=listing_id)
            user.item.remove(item)

            messages.success(request, 'you removed from Wishlist')

        return redirect(reverse("listing", args=[listing_id]))
Answered By: Sunderam Dubey