2đź‘Ť
instance.user = request.user
Well, user is ManyToManyField, you couldn’t just just assign it to model, because it’s “set” of models.
Don’t you want to do this one instead?
instance.user.add(request.user)
0đź‘Ť
First you need this line of code to add user to your objects.
instance.user.add(request.user)
instead of
instance.user = request.user
But, you also need to run some changes to convert the current foreign key user to new M2M user data.
So i would suggest following steps to do first:
1.) Make a new M2M relationship and keep the existing foreign key also.
user = models.ForeignKey(User)
users = models.ManyToManyField(User)
2.) Migrate DB Now.
python manage.py makemigrations
python manage.py migrate
3.) Run following code from terminal to migrate data.
for obj in Model.objects.all():
obj.users.add(obj.user)
4.) Delete the old user field ( Also change users to user, if you wish, but i would recommend to use as users
to reflect plurality. Migrate again.
5.) Make the necessary changes in code like at top to add or process users instead of user.
- [Answered ]-Django many to many field filter using created time
- [Answered ]-Undefined when trying to access json data (ajax)
- [Answered ]-'views' is not defined in Django 1.10