Answer the question
In order to leave comments, you need to log in
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)
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
Answer the question
In order to leave comments, you need to log in
на 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 questionAsk a Question
731 491 924 answers to any question