[Answered ]-Django: 'User' object does not support indexing

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)
👤mingaleg

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.

👤Sachin Gupta

Leave a comment