Django How to fix UnboundLocalError in Models.py

I am getting the following error in models.py, "except Balance.DoesNotExist: UnboundLocalError: local variable 'Balance' referenced before assignment". How can I fix this error? I am trying to create a book keeping website. I have created three classes within my models.py file

Models.py

class Residents(models.Model):
    house_number = models.CharField(max_length=100,unique=True,primary_key=True)
    name = models.CharField(max_length=100)
    contact_number = PhoneNumberField()
            
    def __str__(self):
        return self.house_number + " " + self.name

class Balance(models.Model):
    primary_key=True)
    residents = models.OneToOneField(Residents, on_delete=models.CASCADE, primary_key=True)
    date = models.DateTimeField(default=timezone.now)
    previous_balance = models.DecimalField(max_digits=1000, decimal_places=2 , null=True)
    transaction = models.DecimalField(max_digits=1000, decimal_places=2, null=True)
    def save(self, *args, **kwargs):
        current_balance = self.previous_balance + self.transaction

class Transaction(models.Model):   
    transaction_id = models.CharField(primary_key=True,max_length=100,unique=True)
    residents = models.ForeignKey(Residents, on_delete=models.CASCADE)
    created = models.DateTimeField(blank=True)
    updated = models.DateTimeField(auto_now=True)
    transaction_Amount = models.DecimalField(max_digits=1000, decimal_places=2)
    date = models.DateTimeField()
    def save(self, *args, **kwargs):
        if self.created is None:
            self.created = timezone.now()
        try:
            last_bal = Balance.objects.filter(pk = self.residents).get()
        except Balance.DoesNotExist:
            Balance, Created = Balance.objects.update_or_create(residents = self.residents,date=datetime.date.today(), previouse_balance=last_bal.current_balance,
                               transaction=self.transaction_Amount)
        else:
            Balance.objects.create(residents = self.residents, date=datetime.date.today(), previouse_balance=0.00,
                                transaction=0.00) 

Whenever a new transaction is made I would like the system to first check if the resident have made a transaction yet, if the resident did I would like to update the balance ,else create a new Balance

Error except Balance.DoesNotExist: UnboundLocalError: local variable 'Balance' referenced before assignment

The error is happening due to this line:

Balance, Created = Balance.objects.update_or_create(...)

If a function contains code that assigns to a variable name (in this case Balance), Python assumes that variable is local throughout the entire function (even if you have a global variable of the same name).

But this line of code also refers to Balance on the right hand side, so Python looks for a local variable of that name, and it doesn't find one, so it throws an error.

And in this case I think it's a mistake anyway -- if it had worked the way you wanted, you would have redefined the name Balance, thus erasing the class definition you made earlier.

TL;DR: Use different names for those two local variables.

Back to Top