Django REST framework limits placement and viewing of Api fields

I am using Django Rest framework

JavaScript along with my application. I have some difficulty to get post new items with a commonModelViewSet

Most importantly, I want to limit what the poster can send (they are only allowed to send items that have that user's user_id (authenticated session user).

I don't know when / where should I check this? Is this a verification problem? As far as I understand the permission classes, they limit the (Post / Get) method or validate user groups.

Also my user field in item model

is a foreign key for user model

so the viewable api offers a dropdown list in Html form with information about other users. (their email addresses and some other fields).

My data looks like this

[{
    "id": 792,
    "name": "test",
    "category": 1,
    "value": 5,       
    "user": "33"
}]

      

Here is my Serializer and Viewset:

class ItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = Item
        fields = ('id',
                  'name',
                  'category',
                  'value',
                  'user',
        )

class ItemViewSet(viewsets.ModelViewSet):
    serializer_class = ItemSerializer

    def get_queryset(self):
        return Item.objects.filter(user=self.request.user)

      

+3


source to share


1 answer


User field processing

First, set the user field to read-only:

# serializers.py     

class ItemSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField()
    class Meta:
        model = Item
        fields = ('id',
                  'name',
                  'category',
                  'value',
                  'user',
        )

      

Then automatically set the user id on creation:

# views.py

class ItemViewSet(viewsets.ModelViewSet):
    serializer_class = ItemSerializer

    def get_queryset(self):
        return Item.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user.customer)

      



Processing Permissions

Just use the standard permission mechanism to define a custom one:

# permissions.py

from rest_framework import permissions

class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return (request.user.is_authenticated() and
                (obj.user == request.user.customer))

      

... and use it in your view:

# views.py

from permissions import IsOwner

class ItemViewSet(viewsets.ModelViewSet):
    permission_classes = [IsOwner]
    ...

      

0


source







All Articles