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

Time:05-22

I see this is a common problem and understand the idea is that you cannot add many to many unless it is created first. I have seen multiple solutions for this but unsure which one to use.

Models.py

class Concert(models.Model):
    venue = models.CharField(max_length=200, null=True)
    concertid = models.CharField(max_length = 200, null=False, default='didnotsaveproperly') 
    date = models.DateField(null=True) 
    city = models.CharField(max_length=100, null=True)
    country = models.CharField(max_length=200, null=True)
    user = models.ManyToManyField(USER_MODEL, related_name="concerts", null=True) 
    song = models.ManyToManyField("Song", blank=True, null=True)

    def __str__(self): 
        return str(self.concertid)   " "   str(self.venue)   " "   str(self.date) 

Views.py

def log_concert_and_song(request, concertdict):
    if request.method == "POST":
        Concert_save = Concert(
        concertid=concertdict['id'], 
        date=concertdict['eventDate'], 
        venue=concertdict['venue'], 
        city=concertdict['city'], 
        country=concertdict['country'], 
        user = request.user
        )
 
    Concert_save.save() 

Should I use the User model?

CodePudding user response:

You can add to Many-to-Many relationship by using add Read the docs: https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_many/#many-to-many-relationships

def log_concert_and_song(request, concertdict):
if request.method == "POST":
    Concert_save = Concert(
    concertid=concertdict['id'], 
    date=concertdict['eventDate'], 
    venue=concertdict['venue'], 
    city=concertdict['city'], 
    country=concertdict['country'], 
    )
    Concert_save.save()

    Concert_save.user.add(request.user)

or as error says:

list_of_users = [request.user,]
Concert_save.user.set([list_of_users])
  • Related