Please help to fix the below error: Exception Type: UnboundLocalError at /

Traceback (most recent call last):
File “/Users/shribhamare/Desktop/Coding/DjangoProjects/calorietracker/env/lib/python3.11/site-packages/django/core/handlers/exception.py”, line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File “/Users/shribhamare/Desktop/Coding/DjangoProjects/calorietracker/env/lib/python3.11/site-packages/django/core/handlers/base.py”, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/Users/shribhamare/Desktop/Coding/DjangoProjects/calorietracker/mysite/myapp/views.py”, line 16, in index
consume = Consume(user=user,food_consumed=consume)
^^^^^^^

Exception Type: UnboundLocalError at /
Exception Value: cannot access local variable ‘consume’ where it is not associated with a value

from django.shortcuts import render, redirect
from .models import Food, Consume
from django.core.exceptions import ObjectDoesNotExist


# Create your views here.
def index(request):
 
    if request.method =="POST":
        food_consumed = request.POST['food_consumed']
        try:
            consume = Food.objects.get(name=food_consumed)
        except Exception as e:
            print(e)
        user = request.user
        consume = Consume(user=user,food_consumed=consume)
        consume.save()
        foods = Food.objects.all()
        consumed_food = Consume.objects.filter(user=user)
 
    else:
        foods = Food.objects.all()
        consumed_food = Consume.objects.filter(user=request.user)
 
    return render(request,'myapp/index.html',{'foods':foods,'consumed_food':consumed_food})
 
def delete_consume(request,id):
    consumed_food = Consume.objects.get(id=id)
    if request.method =='POST':
        consumed_food.delete()
        return redirect('/')
    return render(request,'myapp/delete.html')
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
 
class Food(models.Model):
 
    def __str__(self):
        return self.name
 
    name = models.CharField(max_length=100)
    carbs = models.FloatField()
    protein = models.FloatField()
    fats = models.FloatField()
    calories = models.IntegerField()
 
class Consume(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    food_consumed = models.ForeignKey(Food,on_delete=models.CASCADE)

If this block of code throws the exception:

then consume isn’t going to have a value. (It can’t - the query didn’t complete)

As a result, this statement:

will throw the error you are receiving because the reference to consume underlined above is undefined.

When I am printing food_consumed, it has name of a food item. How can I get an object associated with ‘food_consumed’ and get it assigned to ‘consum’? Because as per your explanation consume is undefined or None

In this case, consume is undefined because this query fails:

which means you have no instance of Food where name == food_consumed.