user17408361
user17408361

Reputation:

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.

Upvotes: 0

Views: 330

Answers (2)

arlaine
arlaine

Reputation: 311

Its because your product variable isn't set if you don't go inside if product_form.is_valid():, you could just set a default value before this if statement in order to fix your error.

I hope this helped.

Upvotes: 2

oflint_
oflint_

Reputation: 297

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.

Upvotes: 1

Related Questions