How to restrict access to particular rows in django

2.6k views Asked by At

I am using Django Admin Tool and I have very simple model. I want to restrict access to particular password for specific user or specific group. How can I make 3 condition for access 'Yes/No/Never' and when user has got Yes + his group No then he's got access but when Yes + Never then not. And how can I make it working with django-admin-tools permissions system.

from django.db import models
from passwords.objects.labels.models import Label

class Password(models.Model):
    class Meta:
        db_table = 'passwords'

    name = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    labels = models.ManyToManyField(Label)

    def __unicode__(self):
        return self.name
2

There are 2 answers

0
Burhan Khalid On

Out of the box, django only supports class-level permissions (in other words, permissions on the table).

There is support for object-level (row level) permissions, but django doesn't come with it implemented out of the box:

Object-level permissions

A foundation for specifying permissions at the per-object level has been added. Although there is no implementation of this in core, a custom authentication backend can provide this implementation and it will be used by django.contrib.auth.models.User. See the authentication docs for more information.

Consequently, there are third party apps like django-guardian that enable this functionality.

1
Chris Pratt On

Since you're working with the admin, you can override the has_add_permission, has_change_permission and has_delete_permission methods on ModelAdmin. But, I can't really help you further without knowing how your "Yes/No/Never" permissions are attached to the user/group.

UPDATE

If you want to keep it stupidly simple, the best way would be to simply create a group, "PasswordAccess" for example. Then, assign any users you want to that group, and only assign the default add, change and delete permissions for Password to that group.

Nothing else is required. Any user added to that group will automatically inherit the permissions for Password, any other user won't have those permissions and therefore won't even see it in the admin.