[Fixed]-Django m2m relationship problems

1đź‘Ť

âś…

You’re assigning dog.user in your view, but the field is called owner.

However, I don’t think that you want a many-to-many field here. That would imply that a dog has many owners, and would also mean that you would need to iterate over dog.owner.all in your template. I think instead you want a simple ForeignKey, in which case you can do dog.owner = self.request.user and then output it as you are already doing.

Edit If you’re sure, then you need to add the current user to the list of owners: dog.owner.add(self.request.user). And, as I say, in your display template you can’t just show “the owner” because there are many: you need to iterate over dog.owner.all and show the name of each one.

Leave a comment