0

I'm wanting to create user groups for permissions and am wondering how to do this in the code as it sounds like the more proper way to do it (or not?).

I have done some searching and have found a few completely different pieces of code, but I am not even sure in which file this code should be located? Here is one example that I found:

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Project
new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)

# Now what - Say I want to add 'Can add project' permission to new_group?
permission = Permission.objects.create(codename='can_add_project',
                                   name='Can add project',
                                   content_type=ct)
new_group.permissions.add(permission)

Thank you.

horse
  • 479
  • 7
  • 25
  • You can do it in the Django shell, or in a view you trigger when you want to execute this. – Willem Van Onsem May 05 '20 at 21:46
  • Ah sorry I forgot to mention that I would rather not do it in shell (only because I feel its less proper to do it that way, or maybe i'm wrong?). Is there any particular view which it would make sense to put this in please? P.s. I'm new to coding so this may simply be above my ability atm – horse May 05 '20 at 21:56
  • the question is, *under what circumstances* do you want this to happen? Each time you create a user? or a group? Or only once? Every year? When the user visits a page? Django is a *web development framework*. So normally something should act as a "trigger". – Willem Van Onsem May 05 '20 at 22:00
  • I'd like the creation of the group only to happen once. I'm thinking that would be better to do in my program rather than shell/admin because then it's set and will carry over to production etc. After that I intend on adding newly signed up users to the group (which in itself will be a challenge as new users are currently being generated by allauth so I need to figure out how to change this model) I then want to place a permission on the user profile view restricting access to only those who have signed up. – horse May 05 '20 at 22:30

0 Answers0