7đź‘Ť
This is basic many-to-many stuff:
class Site(models.Model):
site_name = models.CharField(max_length = 512)
allowed_users = models.ManyToManyField(User)
...
sam = User.objects.get(username = 'sam')
frodo = User.objects.get(username = 'frodo')
hobbithole = Site.objects.get(site_name = 'The Hobbit Hole')
hobbithole.allowed_users.add(sam, frodo)
frodo.site_set.all() # Should return "The Hobbit Hole" object, and any other place frodo's allowed to visit.
somesite.allowed_users.exists(user = frodo) # returns True if frodo is in the site's set of allowed users.
If you don’t want to clutter Site
, you can also create an intermediate “through” table. That creates a layer of indirection, but allows you to add things to the through table like degrees of permission, if you want. You can use the auth
module’s groups
feature on that table to define “groups that have access to the keys” and “groups that can modify the property” and so on.
2đź‘Ť
This came up recently, but I can’t find the relevant question on SO. Instead here are some links that I had saved from that discussion to read later:
- Handling object permissions – Django Docs
- Django Object Permissions 1.2 – Oregon State University Open Source Lab
- Django Object Permissions Proof of Concept – The Washington Times
2đź‘Ť
Django now supports object permissions. Besides Handling Object Permissions, which has been linked to in another answer, the REST Framework guide to permissions is worth reading.
You will want to add code to the Meta
subclass of your model for each permission:
class Meta:
permissions = (
('edit_this_model', 'Edit this model'),
)
If you are using south, you may need to run manage.py syncdb --all
after updating the model.
To test if a user is authenticated, use a command such as this:
user.has_perm('your_app_name. edit_this_model')
- Django 1.2 object level permissions – third party solutions?
- Django SQL query duplicated n times
- How to disable resize textarea in django?
- How to open an SSH tunnel using python?
- Django – End of script output before headers
- Django pre_save signal does not work
- Django python 'sql_server.pyodbc' isn't an available database backend
- Jinja {% extends %}
- Django: Forbidden (CSRF cookie not set.)
1đź‘Ť
Try Django-Guradian. You can use it to assign object level permissions to Users/Groups.