36

I need to implement user rights for user groups (pretty similar to facebook groups). For example, each group can have members with rights like: can_post, can_delete, can_ban, etc. Of course, one user can be a member of many groups and group can have many different users with different rights.

What models I need for this functionality?

Braiam
  • 1
  • 11
  • 47
  • 78
duke_nukem
  • 647
  • 2
  • 9
  • 16

1 Answers1

67

Django has a built in groups system. Whenever you have a question like this, I recommend searching the Django docs, which are extensive, helpful, and well written.

So long as you are using the django.contrib.auth app, you have access to groups. You can then assign permissions to those groups.

from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
permission = Permission.objects.create(codename='can_publish',
                                       name='Can Publish Posts',
                                       content_type=content_type)
user = User.objects.get(username='duke_nukem')
group = Group.objects.get(name='wizard')
group.permissions.add(permission)
user.groups.add(group)
Jordan Reiter
  • 20,467
  • 11
  • 95
  • 161
  • 8
    in which file do you usually put this piece of code? – Julio Marins Mar 25 '16 at 05:39
  • The code above creates records, so it's the sort of thing you'd run from within the shell. If you wanted to distribute your app or deploy it, you'd need to set it up so that this initial data was saved. I believe you can also modify them within the admin on the website. – Jordan Reiter Mar 25 '16 at 21:23
  • same thing I did with mine, did that on shell or admin and then generated a fixture to load on future instances of the application. Thanks for the reply – Julio Marins Mar 25 '16 at 22:00
  • 3
    Yeah, but how do you deploy this? Fixtures have been depreciated :-? – CpILL May 18 '16 at 09:59
  • 1
    According to the current documentation, fixtures seem to still be acceptable: https://docs.djangoproject.com/en/1.9/howto/initial-data/ In fact, it appears the deprecation notice was removed. So Django people are not being clear at all what the support actually is. – Jordan Reiter May 26 '16 at 17:34
  • 5
    Custom permissions can be defined in model's `Meta` class and they'll be automatically created on `manage.py migrate`. More details in [the docs](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-permissions). – polart Jun 02 '16 at 16:32
  • @JordanReiter, link is dead... – nerdoc Feb 05 '22 at 16:09
  • 1
    @nerdoc https://docs.djangoproject.com/en/stable/howto/initial-data/ guaranteed working forever. – Braiam Mar 02 '22 at 16:50