# local variable 'form' referenced before assignment

**URL:** <https://forum.djangoproject.com/t/local-variable-form-referenced-before-assignment/8816>\
**Category:** Using Django\
**Created:** [July 17, 2021, 5:56am UTC](https://forum.djangoproject.com/t/local-variable-form-referenced-before-assignment/8816 "2021-07-17T05:56:34Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![dipok\_ray](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/dipok_ray/32/5191_2.png) [@dipok\_ray](https://forum.djangoproject.com/u/dipok_ray)\
**Post date:** [July 17, 2021, 5:56am UTC](https://forum.djangoproject.com/t/local-variable-form-referenced-before-assignment/8816/1 "2021-07-17T05:56:34Z")

</div>

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](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’] |

---

<div class="post-metadata">

**Author:** ![carltongibson](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/carltongibson/32/267_2.png) [@carltongibson](https://forum.djangoproject.com/u/carltongibson)\
**Post date:** [July 17, 2021, 6:36am UTC](https://forum.djangoproject.com/t/local-variable-form-referenced-before-assignment/8816/2 "2021-07-17T06:36:17Z")

</div>

The line where you create the form:

> [@dipok\_ray](#):
>
> ```auto
> form = ProductVoucherForm(request.POST)
> 
> ```

— 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.

---

<div class="post-metadata">

**Author:** ![dipok\_ray](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/dipok_ray/32/5191_2.png) [@dipok\_ray](https://forum.djangoproject.com/u/dipok_ray)\
**Post date:** [July 17, 2021, 8:27am UTC](https://forum.djangoproject.com/t/local-variable-form-referenced-before-assignment/8816/3 "2021-07-17T08:27:01Z")

</div>

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)
```

---

<div class="post-metadata">

**Author:** ![MDFARHYN](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mdfarhyn/32/4519_2.png) [@MDFARHYN](https://forum.djangoproject.com/u/MDFARHYN)\
**Post date:** [July 17, 2021, 4:32pm UTC](https://forum.djangoproject.com/t/local-variable-form-referenced-before-assignment/8816/4 "2021-07-17T16:32:15Z")

</div>

> [@dipok\_ray](#):
>
> ```auto
> context = {
> 'form': form,  
> 'all_data': total_data
> }
> 
> ```

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

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

```

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