Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead

I am getting this error when I try to add the current logged in user into another relation as ManyToManyField.

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead.

Here is my code:

Views.py

def add_to_cart(request , item):
    name = item
    size = request.POST.get("size")
    extras = request.POST.get("extras")
    c = Cart(item=name , size=size , extras=extras , user=request.user)
    c.save()
    return render(request , "orders/add_items.html" , {"message":f"{name} added to cart"})

Models.py

class Cart(models.Model):
    item = models.CharField(max_length=64)
    size = models.DecimalField(max_digits=5,decimal_places=2)
    extras = models.CharField(max_length=64 , null=True, blank=True)
    user = models.ManyToManyField(User , related_name="member")

def __str__(self):
    return f"{item} added by {user}"
like image 875
haider Avatar asked Sep 13 '18 13:09

haider


1 Answers

You need to save the cart before you can add items to the many-to-many field.

c = Cart(item=name , size=size , extras=extras)
c.save()
c.user.add(request.user)

You could also use set() after saving. Note this will remove any related users not specified in the set (although in this case it's a new list so there aren't any).

c.user.set([request.user]

Finally, are you sure you want a many-to-many field for this? That allows a cart to belong to multiple users. If that's the case, I would name the field users, not user. If you only want one user per cart, then I would use a ForeignKey instead. Your related_name members doesn't make sense either. This is used to get the carts related to a user, so I would expect you to use carts instead.

like image 151
Alasdair Avatar answered Oct 30 '22 18:10

Alasdair