1

Im new using Django, Im coding for an ecommerce and everything is working as expected but an error raised even when the code is working!

Sorry for spanglish:

id = request.POST.get('id')
tamano = request.POST.get('size')
items = request.POST.get('items')
precio = request.POST.get('prize')
urlFoto = Producto.objects.filter(id=id).values("urlFoto")
nombre = Producto.objects.filter(id=id).values("nombre")
item = ItemCarrito(id, tamano, items, precio, urlFoto[0]['urlFoto'], nombre[0]['nombre'])
print(item)
controlCambio=False
if request.session.get('lista'):
    lista = request.session.get('lista')
    for posicion in range(0, len(lista)) :
        if lista[posicion].idItem == id and lista[posicion].variante1 == tamano:
            lista[posicion].unidades = int(item.unidades) + int(lista[posicion].unidades)
            print("HAY IGUALES")
            controlCambio=True
    if controlCambio==False:
        lista.append(item)

else:
    lista = []
    lista.append(item)

request.session["lista"] = lista
sumaPrecioCarrito(request, precio)
return detalleProducto(request, id)

The error appears in this line:

item = ItemCarrito(id, tamano, items, precio, urlFoto[0]['urlFoto'], nombre[0]['nombre'])

And it says:

 return qs._result_cache[0]
IndexError: list index out of range

In that line I only create the object ITEM which constructor is:

class ItemCarrito:

def __init__(self, idItem, variante, unidades, precio, urlFoto, nombre):
    self.idItem = idItem
    self.variante1 = variante
    self.unidades = unidades
    self.precio = precio
    self.urlFoto = urlFoto
    self.nombre = nombre

Do you have some ideas of why this error is appearing but everything is working well?

1 Answer 1

0

This error appears when you filter a QuerySet that yields 0 rows and try to use a non-existing index on said QuerySet.

Internally Django will try to run something like

qs = MyModel.objects.filter(id=1) # A filter that returns an empty QuerySet
qs.query.set_limit(index, index + 1) # SELECT * from myapp_amymodel WHERE id = 1 LIMIT 1 OFFSET 1
return qs[0]

In this example, OFFSET value is going to be whatever index you are trying to access on your QuerySet in order to return just one row.

To answer the question, you need to check urlFoto and nombre are non-empty before calling ItemCarrito with those parameters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.