'local variable 'product' referenced before assignment ? in Django
I am facing the issue I can't find the solution yet. It's working so far. but now showing an error. don't know how to fix this. please need help.
views.py
def add_product(request):
product_form = ProductForm()
product_variant_images_form = ProductVariantsImagesForm()
if request.method == 'POST':
product_form = ProductForm(request.POST)
product_variant_images_form = ProductVariantsImagesForm(request.POST,request.FILES)
if product_form.is_valid():
print(request.POST)
product = product_form.save(commit=False)
vendor = CustomUser.objects.filter(id=request.user.id)
product.vendoruser = vendor[0]
product.save()
vendor = CustomUser.objects.get(id=request.user.id)
product_variant = ProductVariants()
product_variant.product_id = product ###ERROR SHOWING IN THIS LINE
product_variant.vendoruser = vendor
product_variant.price = request.POST.get('price')
product_variant.initial_stock = request.POST.get('initial_stock')
product_variant.weight_of_product = request.POST.get('weight_of_product')
product_variant.save()
return redirect('vendor:inventory_display')
else:
productform = ProductForm()
productvariantsform = ProductVariantsForm()
product_variant_images_form = ProductVariantsImagesForm()
return render(request, 'vendor/add_product.html',
{'productform': productform,'product_variant_images_form':product_variant_images_form,
'productvariantsform': productvariantsform})
It's working fine.After product added multiple time the error occurred. how can I get rid of this error.please some help much appreciated.
Solution 1:[1]
The product variable is only defined if the form is valid. Either you can set a default value for product outside of the if statement or you could move all of the code involving data from the form inside of the if statement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | oflint_ |
