User groups and permissions
Asked Answered
K

1

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?

Krawczyk answered 12/9, 2012 at 17:51 Comment(0)
W
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)
Watteau answered 12/9, 2012 at 17:59 Comment(8)
in which file do you usually put this piece of code?Brigade
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.Watteau
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 replyBrigade
Yeah, but how do you deploy this? Fixtures have been depreciated :-?Parmesan
According to the current documentation, fixtures seem to still be acceptable: 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.Watteau
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.Roop
@JordanReiter, link is dead...Cormier
@Cormier docs.djangoproject.com/en/stable/howto/initial-data guaranteed working forever.Conjectural

© 2022 - 2024 — McMap. All rights reserved.