Unboundlocalerror: Local Variable 'prod_available' Referenced Before Assignment
Solution 1:
Sometimes you loop is not entered, so prod_Available is not created, but you try to reference it.
Before the loop put prod_Available = 0:
prod = Product.objects.get(id=product_id)
prod_Available = 0# !for x inrange(start_date,end_date + 1):
x = x - start_date
delta = datetime.timedelta(days=x)
all_date = check_in + delta
sumOfQuantity = HotelCheck.objects.filter(date_booked=all_date, product=prod).aggregate(Sum('quantity'))['quantity__sum']
if sumOfQuantity == None:
sumOfQuantity = 0
prod_Available = prod.quantity - sumOfQuantity
#global prod_Availableif prod_Available <= 0:
status = 0else:
status = 1return status
Solution 2:
Just initialize prod_Available to Zero before the following for statement
for x in range(start_date,end_date + 1):
It so happens that because you are assigning value to prod_Available inside the loop, there is a possibility that the variable is never assigned and the following if statement would fail.
ifprod_Available<=0:Instead, doing
prod_Available =0 #Initialize outside loop
for x in range(start_date,end_date + 1):
would resolve your issue
Solution 3:
You are getting different behaviours due to passing in different values.
For the first call, you are passing check_in='2011-12-15' and check_out='2011-12-10' and for the second, you have checkin='2011-12-10', and checkout='2011-12-15'. I.e, the check in and check out values are swapped.
This means that the for x in range(start_date,end_date + 1): loop will never get executed, thus never setting prod_Available.
There are two obvious fixes here:
Improve parameter validation, and report an error if the check out date is before the check in date.
Set
prod_Availableto zero before you start the loop. This will ensure that it is always set, even if the loop does not execute.
Post a Comment for "Unboundlocalerror: Local Variable 'prod_available' Referenced Before Assignment"