Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django per-object permissions

I have users that each are associated with a list of real estate properties they are allowed to access. Multiple users may have permission to view the same site.

How would I set this up in django?

I have the:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    last_session_time_online = models.IntegerField()
    total_time_online = models.IntegerField()
    def __unicode__(self):
        return self.user

and the

class Site(models.Model):
    site_name = models.CharField(max_length = 512)
    ...Other stuff...
    def __unicode__(self):
        return self.user
like image 279
Goro Avatar asked Sep 01 '11 23:09

Goro


People also ask

Does Django have object permissions?

Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. Object level permissions are run by REST framework's generic views when . get_object() is called. As with view level permissions, an exceptions.

What are object level permissions Django?

Object Permissions allow you to assign a permission to an instance of any Model in your django project. This app provides a authentication backend that works with Django >= 1.2. This specific implementation includes the ability to assign permissions to Users and UserGroups.

How do I check permissions in Django?

To test which users have basic permissions, you can use the following code. view: user. has_perm('product. view_order') Adding permissions to restrict a function to only users that have that particular permission can be done by using a Django built-in decorator, permission_required .


1 Answers

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.

Many To Many Fields in Django

like image 166
Elf Sternberg Avatar answered Oct 22 '22 07:10

Elf Sternberg