4

I have defined the following models

class Flight(models.Model):
    ...

class FlightUpdate(models.Model):
    flight = models.ForeignKey('Flight', related_name='updates')
    ...

and the following viewset using the NestedViewsetMixin in the REST Framework Extensions

class FlightUpdateViewSet(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      NestedViewSetMixin,
                      viewsets.GenericViewSet):
    """
    API Endpoint for Flight Updates
    """
    queryset = FlightUpdate.objects.all()
    serializer_class = FlightUpdateSerializer

    def create(self, request, *args, **kwargs):
        flight = Flight.objects.get(pk=self.get_parents_query_dict()['flight'])
        ...

So, to access the FlightUpdates associated with a Flight, the URL is /flights/1/updates/.

I want to ensure that people can only create FlightUpdates if they have the permissions to change the Flight object with which the FlightUpdate is associated.

How would I go about performing the extra check when adding a FlightUpdate? I've tried adding something like this in the viewset, but I'm not sure if it's the best way.

if not request.user.has_perm('flights.change_flight', flight):
    raise PermissionError()

Note: I'm using django-rules for the object-level permissions implementation.

Kieran
  • 2,554
  • 3
  • 26
  • 38

1 Answers1

3

I solved this problem by implementing a custom permissions class.

from django.core.exceptions import ObjectDoesNotExist

from rest_framework.permissions import BasePermission, SAFE_METHODS

from .models import Flight


class FlightPermission(BasePermission):

    def has_permission(self, request, view):
        if request.method in SAFE_METHODS:
            return True

        try:
            flight = Flight.objects.get(pk=view.kwargs['parent_lookup_flight'])
        except ObjectDoesNotExist:
            return False

        return request.user.has_perm('flights.change_flight', flight)
Kieran
  • 2,554
  • 3
  • 26
  • 38
  • Thansk for it! Went though the same problem. Had read your answer. But needed some hours to catch up you found out the solution! https://stackoverflow.com/questions/52782778/django-drf-permissions-on-create-related-objects/52783914#52783914 – stockersky Oct 12 '18 at 16:54