Search code examples
djangopermissionsmodels

how to create Groups programatically in Django


I am setting up a member site using django, in which members belong to groups that they create and then invite other users to join.

It seems that what I am looking for is to use the django groups functionality, but the documentation on how to go about this is minimal at best - at least I haven't found any. It basically talks about creating groups in the Admin console, which is not what I am trying to do. I would like to do it programatically/dynamically.

Another way to go about this would be to at a foreignkey to the User model up to a group model, however I can't add a foreignkey to the generic User model.

I have read lots of stuff that google threw up at me from my searches. none helpful.

How would I go about this?

Thanks


Solution

  • Well a Group is just another model in Django (one of the models defined in the Django library).

    You can thus create a group with:

    from django.contrib.auth.models import Group
    
    g1 = Group.objects.create(name='Name of the group')
    

    The Group model has two many-to-many relations: one to Users (with related name users), and one to Permission (with related name permissions). So we can use the corresponding managers to add and remove Users and Permissions.

    Then you can for example populate the group with users like:

    g1.user_set.add(user1, user2, user5, user7)
    

    You can also add permissions to a group with:

    g1.permissions.add(perm1, perm3, perm4)