Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set permissions for POST requests in Django REST Framework?

I've got two Django models that are linked like this:

class ParentModel(models.Model):
    creator = models.ForeignKey(User, related_name='objects')
    name = models.CharField(max_length=40)

class ChildModel(models.Model):
    parent = models.ForeignKey(ParentModel, related_name='child_objects')
    name = models.CharField(max_length=40)

Now, when making ViewSet for child model, I want it to be created only if its parent was created by the same user that is creating child instance. The permission class that I'm including into my ChildViewSet(viewsets.ModelViewSet) looks like this:

class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.parent.creator == request.user

This seems to work just fine when i use PATCH method, but POST methods don't seem to notice this permission class even when I explicitly set return False for POST method.

What am I doing wrong and how to fix it?

like image 470
Oleh Omelchenko Avatar asked Sep 02 '25 06:09

Oleh Omelchenko


1 Answers

Thanks to wim for providing me with a hint to an answer!

The reason why my permission didn't work with POST requests is, indeed, that the object has not yet been created and so I should use has_permission in my permission class. Here's the code that worked for me:

def has_permission(self, request, view):
    user_id = getattr(request.user, 'id')
    parent_id = request.data['parent']
    if parent_id is not None:
        parent_obj = ParentModel.objects.get(id=parent_id)
        serialized = ParentSerializer(association)
        return user_id == serialized.data['creator']
    return False
like image 133
Oleh Omelchenko Avatar answered Sep 04 '25 19:09

Oleh Omelchenko