Python Forum

Full Version: Error - ManyToMany Fields in Django
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have this error in Django :
Quote: __str__ returned non-string (type SimpleLazyObject)

idk why..
I'm learning Django and I don't know to use ManyToMany Relations in Db Well.

This is my code.. where 's the error ?


in models.py

from macelleria_app.models import Prodotti


class Cart_item (models.Model):


    product = models.ForeignKey (Prodotti, on_delete=models.CASCADE)
    quantity = models.FloatField (default=0)



    def __str__ (self):
        return self.product




class Cart (models.Model):
    cart_user = models.ForeignKey(User, on_delete=models.CASCADE)
    prodotti= models.ManyToManyField(Cart_item)
    a="3"

    def __str__ (self):
        return self.a




    def __str__ (self):
        return self.cart_user
in views.py :
def carrello (request):

    carrello = Cart.objects.get(cart_user=request.user)
    prodotti_carrello = carrello.prodotti
    print (carrello)

    context = {'prodotti_carrello': prodotti_carrello}
    return render (request,'carrello.html', context)


@login_required
def aggiungi_carrello (request, product_id, quantity):

    product_id_1 = int (product_id)
    quantity_1 = int (quantity)
    carrello_utente = Cart ()
    carrello_utente.cart_user= request.user


    ordine_item = Cart_item()
    articolo_1= Prodotti.objects.get (id=product_id_1)
    ordine_item.product = Prodotti.objects.get (id=product_id_1)
    ordine_item.quantity= quantity_1
    ordine_item.save()


    carrello_utente.prodotti.set(ordine_item)

    carrello_utente.save ()
    return HttpResponse ('/carrello'). #I'm working to render the real Cart
and in urls.py there is a string like "path('carrello/update/<product_id>/<quantity>/', views.aggiungi_carrello, name='update_cart') "

somebody who can help me?