Home > Net >  local variable 'product' referenced before assignment
local variable 'product' referenced before assignment

Time:12-03

I am trying to create a django view which will let users to create a new product on the website.

class CreateProductView(APIView):
    serializer_class = CreateProductSerializer

    def post(self, request, format = None):
        

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            name = serializer.data.name
            content = serializer.data.content
            category = serializer.data.category

            product = Product(name=name, content=content, category=category)
            product.save()

        return Response(ProductSerializer(product).data, status=status.HTTP_201_CREATED)

But it is giving this error:

UnboundLocalError at /api/create-product
local variable 'product' referenced before assignment
Request Method: POST
Request URL:    http://127.0.0.1:8000/api/create-product
Django Version: 4.0.5
Exception Type: UnboundLocalError
Exception Value:    
local variable 'product' referenced before assignment
Exception Location: H:\Extension Drive (H)\My Software Applications\DeCluttered_Life\declutterd_life\api\views.py, line 42, in post
Python Executable:  C:\Python310\python.exe
Python Version: 3.10.5
Python Path:    
['H:\\Extension Drive (H)\\My Software '
 'Applications\\DeCluttered_Life\\declutterd_life',
 'C:\\Python310\\python310.zip',
 'C:\\Python310\\DLLs',
 'C:\\Python310\\lib',
 'C:\\Python310',
 'C:\\Python310\\lib\\site-packages']
Server time:    Fri, 02 Dec 2022 17:26:24  0000

I tried to look other issues similar to this, but couldn't find the solution.

CodePudding user response:

You are trying to reference the product variable before it has been assigned when serializer.is_valid() is False.

You should move the response line inside the if statement, so that it is only returned if serializer.is_valid() is True and handle the response for invalid serializer with an http error for example.

CodePudding user response:

Check if the serializer.is_valid() returns True. If it doesn't, your code attempts to return a Response object, which uses the product variable. However, if your serializer.is_valid() does returns False, the Response is still created with the product variable, which has not been created yet.

It might be wise to write functionality that handles the situation when your serializer.is_valid() returns False. In that case, probably you don't need the product variable.

  • Related