Django "view-permissions" for related objects

Feb. 9, 2010 - Joeri - django - admin - permissions - Development

We're very busy at the moment, hence there are not a lot of blog posts lately. A quick text dump of what I wanted to write follows:

We came to the point where every Django developer wants to add the infamous "view"-permission to the Django admin interface. Our use case is a little simpler but I think many people can come across this:

You have a model A with a relation to another model B. In the Django admin, you have full permissions for model A and none for model B. However, if you create a new object for model A, you need to select a related object from model B. Tough luck: Permission denied!

class B(models.Model):
    name = models.CharField(max_length=20)

class A(models.Model):
    name = models.CharField(max_length=20)
    b = models.ForeignKey(B)

After looking at various projects that either patch the whole admin or add row-level permissions, I found that this particular issue could be solved with just 2 (or 3 if you don't have an "options" class yet) lines of code in your

class MyAdmin(admin.ModelAdmin):
    def has_change_permission(self, request, obj=None):
        return request.GET.get('pop', None) == '1' or \
            super(BaseCoreOptions, self).has_change_permission(request, obj)

It's a hack, it's not pretty but it works. These 2 lines of code allow you to select a related object if the list is requested with the pop=1 parameter.

Latest Tweets