1

I have two models Community and User. In the Community model I am creating a field ManyToManyField called member (based on the User Model) i.e. a community object may have many members and a member object may belong to many communities. The issue I am encountering is that I cannot remove a member from a community neither from within the class-based view.py nor from within the admin page .

Creating the ManyToMany relation between Community and User with the field name member.

class Community(models.Model):
    member = models.ManyToManyField(User, related_name='member')

Code in class-based view.py for removing a member from a community object (removing only the relation, not the related object itself)

class CommunityListView(ListView):
    model = Community

    def get(self, request, *args, **kwargs):
        # The url contains the community id (pk)
        community_id = kwargs['pk']
        c = Community.objects.get(id=community_id)
        u = User.objects.get(id=self.request.user.id)
        c.member.remove(u)

        return super(ListView, self).get(request, *args, **kwargs)

The code is executed without error but when I visit the admin page the member is still there. I have tried to run c.save() after the command c.member.remove(u) but without success either. As I have understood, Django doc says that the method save() is not needed when you remove a relation from a ManyToManyField.

Furthermore, as you can see from the attached image [admin page] I cannot remove manually a member (orfanos, NewUser) from within the admin page. There is only a plus sign for adding a member but not a minus sign for removing a member.

I know there are similar questions which recommend the usage of the method remove() but none of them worked for me. Furthermore, I am a new member in stackoverflow without credits, thus I couldn't comment in any related question of mine. I attach 2 links of the most related questions: relatedQuestion1, relatedQuestion2.

The answer in the relatedQuestion1 with the raw_id_fields in order to update a relation didn't satisfy me because this seems to be an alternative way of searching for your related objects by their ids rather than a way of removing a relation.

1 Answers1

0

Finally, it was working properly.

Under the method get() within the class CommunityListView I printed twice the members of the community (c) before and after the command c.member.remove(u) and I could see in the terminal the removal of the user (u).

    print(c.member.all())
    c.member.remove(u)
    print(c.member.all())

It was confusing though, the way the m2m field is displayed in the admin page as it always displays all the users whether or not they are members of the community (see my uploaded pic in the posted question in the link "admin page")