O
O
Oleg2016-07-22 16:41:12
Django
Oleg, 2016-07-22 16:41:12

How to set permissions to create a child object?

The two models are related as follows:

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)

When forming a ViewSet for a child model, I specify permission_classes:
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

It was established by typing that this class (in addition to SAFE_METHODS) works correctly with the PATCH method, but for some reason, with POST, any user can create a child object with a parent that does not belong to this user.
In settings.py in the permissions settings there is only 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' Poke
into the docks, which I missed here.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Олег, 2016-07-23
@ptrvch Автор вопроса

на SO подсказали, что метод POST не работает с существующим объектом, поэтому нужно указывать логику в has_permission:

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(parent_obj)
        return user_id == serialized.data['creator']
    return False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question