Oleg Omelchenko Oleg Omelchenko - 4 months ago 25
Python Question

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?

wim wim
Answer

It's hard to know for sure without seeing your urls and views, but please look at the default methods implemented in BasePermission which you inherit:

def has_permission(self, request, view):
    """
    Return `True` if permission is granted, `False` otherwise.
    """
    return True

def has_object_permission(self, request, view, obj):
    """
    Return `True` if permission is granted, `False` otherwise.
    """
    return True

For PATCH you're working with an object which already exists, and you go into the custom method that you've overridden - OK! For POST, you may be hooking into the other one, because you're creating a new object.

So, try implementing has_permission in your derived class.