Reputation: 4008
I've a View that, according to my prints, enters the Try
and the Except
parts.
As far as I understand, it only should enter the Try
part or the Except
part not both.
Cart object exist
Lenght in Cart_Items
1
Enters Except PART
55
Why could this be happening?
def cart_detail(request, total = 0, counter = 0, cart_items = None):
try:
cart = Cart.objects.get(id = request.COOKIES.get("cart_id"))
if not cart:
print("No Cart object")
else:
print("Cart object exist")
cart_items = CartItem.objects.filter(cart = cart)
print("Lenght in Cart_Items")
print(len(cart_items))
for cart_item in cart_items:
total += (cart_item.product.price)
sample_items = SampleItem.objects.filter(cart=cart)
for sample_item in sample_items:
total += (sample_item.sample.price)
culqi_my_public_key = settings.CULQI_PUBLISHABLE_KEY #Es necesario mandar la llave pública para generar un token
culqi_total = int(total * 100) #El total para cualqui debe multiplicarse por 100
categories = Category.objects.exclude(name='Muestras')
return render(request, 'cart.html', dict(cart_items = cart_items, sample_items = sample_items, total = total, counter = counter,
culqi_total = culqi_total, culqi_my_public_key = culqi_my_public_key,
categories = categories))
except:
print('Enters Except PART')
print(request.COOKIES.get("cart_id"))
categories = Category.objects.exclude(name='Muestras')
return render(request, 'cart.html', {'categories':categories})
Upvotes: 0
Views: 40
Reputation: 31260
Your understanding is wrong. The code always enters the try:
part, until an exception is raised. If and when that happens, the except:
part is run.
So you get the first part of your try:
, and then the except:
. Code at the end of the try:
isn't reached.
Your try:
part is very long, and you have a so-called "bare-except": you don't say which exceptions you want to catch. Both aren't a good idea, it's better to have short try-parts (so you know exactly which line might throw an exception) and then to catch exactly that exception you expect and nothing else. Otherwise unexpected exceptions will happen without you noticing, because they're silenced by the except:
block.
Upvotes: 1
Reputation: 485
Your code will be breaking after print(len(cart_items))
statement in the try block and then its entering the except block.
Upvotes: 0