0

I am trying to use a link to add items to a cart but it keeps saying that I am referencing the variable before it assigned.

views.py:
def view(request):
    cart = Cart.objects.all()[0]
    products = Product2.objects.all()
    context = {
    "cart": cart,
    "products": products
    }
    template = "cart/view.html"
    return render(request, template, context)

def update_cart(request, slug):
    cart = Cart.objects.all()[0]
    try:
        product = Product2.objects.get(slug = slug)
    except Product2.DoesNotExist:
        pass
    except:
        pass
    if not product in cart.products.all():
        cart.products.add(product)
    else:
        cart.products.remove(product)
    return HttpResponseRedirect(reverse("cart"))

models.py:

class Product2(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField()
    slug = models.SlugField()

    def __str__(self):
        return self.name        


html:

{% for product in products %}
<div>
    <h1>{{ product.name }}:  ${{ product.price }}<a href='{% url "update_cart" product.slug %}' class ='pull-right'>Add to Cart</a></h1>
</div>
{% endfor %}

I had it working for a second but I created a new table in the database, changed the name where applicable, and now it doesn't work.

remious
  • 1
  • 2

1 Answers1

0

In update_cart, if an exception is raised during product = Product2.objects.get(slug = slug), then product will not be defined and the line if not product in cart.products.all() will raise the UnboundLocalError.

You may fix this by only proceeding with the following code, which uses product if no exception was raised:

def update_cart(request, slug):
    cart = Cart.objects.all()[0]
    try:
        product = Product2.objects.get(slug = slug)
    except Product2.DoesNotExist:
        pass
    else:
        if not product in cart.products.all():
            cart.products.add(product)
        else:
            cart.products.remove(product)
    return HttpResponseRedirect(reverse("cart"))

The else clause to try/except here will only be executed if no exception was raised by the code inside try, meaning that you won't try to use product unless it has been successfully defined.

As a side note, I recommend avoiding the bare except, since this would mask any problems/interrupts that occur during execution of your code (see this question).

dspencer
  • 4,297
  • 4
  • 22
  • 43