Adding per-object permissions to django admin

Viewed 10485

Background

I'm developing a django app for a vacation rental site. It will have two types of users, renters and property managers.

I'd like the property managers to be able to manage their rental properties in the django admin. However, they should only be able to manage their own properties.

I realize the default django admin doesn't support this. I'm wondering how much trouble it would be to add this functionality, and, if it's feasible, what the best way to handle it is.


Goal

Ideally, I picture it working something like this:

auth already allows permissions like this:

vacation | rental | Can add rental
vacation | rental | Can change rental
vacation | rental | Can delete rental

I'd like to change this to something like:

vacation | rental | Can add any rental
vacation | rental | Can change any rental
vacation | rental | Can delete any rental
vacation | rental | Can add own rental
vacation | rental | Can change own rental
vacation | rental | Can delete own rental

Possible solution

How would the framework decide if the rental (or whatever) belongs to the user? I'm thinking it checks the vacation.Rental class to see if it has a ForeignKey to auth.User (possibly having some particular name, like 'owner').

  • On creating a new vacation.Rental, the value of the ForeignKey field would be forced to the current user's id. The ForeignKey field would not be displayed on the form.

  • On listing rentals, only rentals with the ForeignKey matching the current user would be displayed.

  • On changing rentals, only rentals with the ForeignKey matching the current user would be displayed. The ForeignKey field would not be displayed on the form.

Of course, this should be able to work for any model having an appropriate ForeignKey field, not just our vacation.Rental model.

Does this sound feasible so far, or should I be going in a different direction?


Complications

Now, here's the tricky part; I'm not sure how to handle this. Let's say a Rental can have many "RentalPhotos." RentalPhoto has a ForeignKey to Rental. Users should be able to add photos to their own rentals. However, the photos don't have a user ForeignKey, so there's no way to directly find out who owns the photo.

Can this be solved by some trickery in the framework, following ForeignKeys until an object is found with a ForeignKey to user? Or should I take the easy way out and give RentalPhoto (and everything else 'belonging' to Rental) its own ForeignKey to the appropriateauth.User? The second approach would invite unneeded redundancy, the first would probably require unnecessary processing overhead...

If I'm going entirely astray please don't hesitate to point me in the right direction. Thanks in advance for any help.

5 Answers
class Rental(models.Model):
    owner: User = models.ForeignKey(
        User, verbose_name='owner', related_name='rentals',
        on_delete=models.CASCADE, blank=True, null=False
    )
    # owner_id automatically gets created by Django. Optionally annotate to help your IDE
    owner_id: int

    def is_owned_by(self, user: User):
        # You can use self.owner == user, or self.owner.id == user.id. 
        # But this way owner data won't be fetched from the database
        if self.owner_id == user.id:
            return True
        return False


class RentalPhoto(models.Model):

    rental: Rental = models.ForeignKey(
        Rental, on_delete=models.CASCADE, related_name='rental_photos',
        blank=False, null=False,
    )

    def is_owned_by(self, user: User):
        return self.rental.is_owned_by(user)


class RentalPhotoAdminInline(admin.StackedInline):
    model = RentalPhoto
    extra = 1


@admin.register(Rental)
class RentalAdmin(admin.ModelAdmin):

    inlines = (RentalPhotoAdminInline,)

    # staff members can only view/operate their rentals
    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        if not request.user.is_superuser:
            queryset = queryset.filter(owner_id=request.user.id)

        return queryset

    def save_model(self, request, obj: Rental, form, change):
        # set rental owner on admin save
        if obj.owner_id is None:
            obj.owner = request.user
        obj.save()

    def has_view_or_change_permission(self, request, obj=None):
        allowed = super().has_view_or_change_permission(request, obj)
        if obj is None:
            return allowed
        return request.user.is_superuser or obj.is_owned_by(request.user)

    def has_view_permission(self, request, obj=None):
        allowed = super().has_view_permission(request, obj)
        if obj is None:
            return allowed
        return request.user.is_superuser or obj.is_owned_by(request.user)

    def has_change_permission(self, request, obj=None):
        allowed = super().has_change_permission(request, obj)
        if obj is None:
            return allowed
        return request.user.is_superuser or obj.is_owned_by(request.user)

    def has_delete_permission(self, request, obj=None):
        allowed = super().has_delete_permission(request, obj)
        if obj is None:
            return allowed
        return request.user.is_superuser or obj.is_owned_by(request.user)
Related