I’m trying to build a wish list for my website. So I created a view that will
- render out the wish list and to
- add items to the wish list – using ajax
Those two tasks are carried out by the same view. Here’s how I did it,
views.py
@login_required(login_url='/login')
def wishlist(request):
wishes = Wishlist.objects.filter(customer=request.user.customer).prefetch_related(
Prefetch('product',
queryset=Product.objects.prefetch_related(
Prefetch(
'productimage_set',
ProductImage.objects.filter(place='Main Product Image'),
to_attr='main_image'
),
),
to_attr='wished_dish'
),
)
# delete wished dish
if request.method == 'POST':
dish_to_delete = request.POST.getlist('delete_items')
print(dish_to_delete)
Wishlist.objects.filter(pk__in=dish_to_delete).delete()
# question is related to below statements
if request.method == 'GET':
try:
dish_id = request.GET('dish_id')
dish = Product.objects.get(id=dish_id)
wish, created = Wishlist.objects.get_or_create(
customer=request.user.customer,
product=dish
)
if created:
return HttpResponse('Dish <b>{}</b> Added to wish list!'.format(dish.name))
else:
return HttpResponse('Dish <b>{}</b> is already in your wish list!'.format(dish.name))
except:
pass
context = {
'wishes': wishes,
}
return render(request, 'store/wishlist.html', context)
As you can see I’ve used a try:... except: pass
block for GET requests
to separate the adding functionality and viewing functionality.
It works fine but is this the optimal way to achieve the intended goal?