local variable 'form' referenced before assignment

Hi Everyone,
I am creating a indent management system ,I want to get current user as a input, but I can’t fixed it .

forms.py

from django import forms

from django.contrib.auth.forms import UserCreationForm

from django.contrib.auth.models import User

from .models import Product, Indent

class ProductVoucherForm(ModelForm):

requested_amount = forms.FloatField(required=False)

paid_amount = forms.FloatField(required=False)

balance = forms.FloatField(required=False)

class Meta:

    model = Indent

    fields = [ "category", "product", "product_price", "product_quantity", "requested_amount", "paid_amount",

              "balance"]

models.py

class Indent(models.Model):

user = models.ForeignKey(Profile, on_delete=models.CASCADE)

category = models.ForeignKey(Category, on_delete=models.CASCADE)

product = models.ForeignKey(Product, on_delete=models.CASCADE)

product_price = models.FloatField(blank=True)

product_quantity = models.IntegerField(null=True)

requested_amount = models.FloatField(null=False, blank=True, default=0)

paid_amount = models.FloatField(null=True, default=0)

balance = models.FloatField(null=True, default=0)

def save(self, *args, **kwargs):

    self.requested_amount = self.product_price * self.product_quantity

    self.balance = self.requested_amount - self.paid_amount

    super(Indent, self).save(*args, **kwargs)

def __str__(self):

    return self.category

views.py

def ProductVoucher(request):
if ‘q’ in request.GET:
q = request.GET[‘q’]
all_data = Indent.objects.filter(id__icontains=q)
else:
all_data = Indent.objects.all()

paginator = Paginator(all_data, 15)  # Show 15 contacts per page.
page_number = request.GET.get('page')
total_data = paginator.get_page(page_number)

if request.method == "POST":
    if request.user.is_authenticated:

        form = ProductVoucherForm(request.POST)

        for field in form:
            print(field.value())

        if form.is_valid():
            obj = form.save(commit=False) # Return an object without saving to the DB
            obj.user = Profile.objects.get(pk=request.user.id) # Add an author field which will contain current user's id
            obj.save() # Save the final "real form" to the DB
        else:
            print("ERROR : Form is invalid")
            print(form.errors)
        
context = {
    'form': form,  
    'all_data': total_data
         }
return render(request, 'product_voucher.html', context)

now i get this error :
local variable ‘form’ referenced before assignment

Request Method: GET
Request URL: http://127.0.0.1:8000/product/voucher
Django Version: 3.1.7
Exception Type: UnboundLocalError
Exception Value: local variable ‘form’ referenced before assignment
Exception Location: E:\python project\Indent-management\indentapp\views.py, line 115, in ProductVoucher
Python Executable: C:\Program Files\Python37\python.exe
Python Version: 3.7.5
Python Path: [‘E:\python project\Indent-management’, ‘C:\Program Files\Python37\python37.zip’, ‘C:\Program Files\Python37\DLLs’, ‘C:\Program Files\Python37\lib’, ‘C:\Program Files\Python37’, ‘C:\Users\user\AppData\Roaming\Python\Python37\site-packages’, ‘C:\Program Files\Python37\lib\site-packages’, ‘C:\Program Files\Python37\lib\site-packages\win32’, ‘C:\Program Files\Python37\lib\site-packages\win32\lib’, ‘C:\Program Files\Python37\lib\site-packages\Pythonwin’]

The line where you create the form:

— is only referenced inside the if request.method == "POST": block, so for a GET request form is not set.

You need to make sure form is created on both paths.

i am using this but i can’t fixed it please tell me what can i do now ?

if request.method == “POST”:

    if request.user.is_authenticated:

        form = ProductVoucherForm(request.POST)

        for field in form:

            print(field.value())

        if form.is_valid():

            obj = form.save(commit=False) # Return an object without saving to the DB

            obj.user = Profile.objects.get(pk=request.user.id) # Add an author field which will contain current user's id

            obj.save() # Save the final "real form" to the DB

        else:

            print("ERROR : Form is invalid")

            print(form.errors)

your are getting local variable ‘form’ referenced before assignment this error for this line of code:

context = {
    'form': form,  
    'all_data': total_data
         }

your form variable not found in context because it’s inside the loop.