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]))