5

I need to make an "owners" login for the admin. Say we have this model structure:

class Product(models.Model):
    owner = models.ManyToManyField(User)
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    photos = models.ManyToManyField(Photo, through='ProductPhoto')


class Photo(models.Model):
    order = models.IntegerField()
    image = models.ImageField(upload_to='photos')
    alt = models.CharField(max_length=255)


class ProductPhoto(models.Model):
    photo = models.ForeignKey(Photo)
    product = models.ForeignKey(Product)

We have a group called Owners that some users are part of. The ProductPhoto is a TabularInline on the Product admin page.

Now, owners need permission to edit

  1. (primary goal) only products where product__in=user.products (so basically, only products owned by them).

  2. (secondary goal) only the description and photos of products

How would I do this with Django's admin/permission system?

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
antihero
  • 423
  • 5
  • 10

2 Answers2

4

This is row (or object) level permission. Django provides basic support for object permissions but it is up to you to implement the code.

Luckily, there are a few apps that provide drop-in object-level permission framework. django-guardian is one that I have used before. This page on djangopackages.com provides some more that you can try out.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 3
    Actually - this is a better djangopackages page: http://www.djangopackages.com/grids/g/perms/ – Andy Baker Jun 21 '12 at 14:33
  • Ah, field level is what I need also now. Is there a way to implement this on top of guardian? Or does another framework provide this? – antihero Jul 23 '12 at 22:32
0

You may implement using get_form. For complex rule, you can add this too: https://github.com/dfunckt/django-rules

  def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)        
    # permission check;         
    if form.base_fields and not request.user.is_superuser:
        # when creating or updating by non-reviewer (except superuser)
        # allow only reviewer to allow updating
        form.base_fields['usertype'].disabled = True 
AndyC
  • 109
  • 2
  • 4