Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 575
Bigga Avatar asked Jun 04 '18 12:06

Bigga


People also ask

How do I set permission and group in Django?

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.

What is groups in Django?

Django does provide groups and permissions option but this is a model or table level and not at the object level. Hence we decided on creating groups based on the objects on which we want to provide the access and the users were added to these groups as per requirement or based on the existing state of an object.

What is PermissionsMixin in Django?

The PermissionsMixin is a mixin for models. The PermissionsMixin [Django-doc] is a mixin for Django models. If you add the mixin to one of your models, it will add fields that are specific for objects that have permissions, like is_superuser , groups , and user_permissions .

What are groups in Django admin?

Groups are a means of categorizing users. This allows for granting permissions to a specific group.


1 Answers

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)
like image 102
Willem Van Onsem Avatar answered Sep 22 '22 09:09

Willem Van Onsem