简体   繁体   English

分配之前引用的局部变量“产品”? 在 Django

[英]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视图.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.我怎样才能摆脱这个错误。请提供一些帮助,非常感谢。

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.这是因为如果您没有 go 内部if product_form.is_valid(): ,则您的产品变量未设置,您可以在此 if 语句之前设置默认值以修复您的错误。

I hope this helped.我希望这会有所帮助。

The product variable is only defined if the form is valid.仅当表单有效时才定义product变量。 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.您可以在 if 语句之外为product设置默认值,也可以将所有涉及数据的代码从 if 语句内部的表单中移出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM