adarsh
adarsh

Reputation: 51

Django Rest Framework Authentication Issues

I am a newbie in Django. I had created REST API using DRF. My Django has 3 apps. So now I want to apply authentication. I have seen much help but I am not to apply the authentication properly. I also want that the model should be attached to the user. So that one user can't see another user entries. Can anyone help me in telling how to implement this a little detailed?

Thanks in advance. Will be a great help if someone answers.

Upvotes: 1

Views: 120

Answers (1)

zaidfazil
zaidfazil

Reputation: 9245

You could add custom permissions,

class IsOwnerOnlyAllowed(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user

You may add permission_classes = (IsOwnerOnlyAllowed,)

Also, you could override the queryset attribute of your view to provide only entries which are related to the logged in users.

Edit your views,

from rest_framework import generics 
from .models import DatasetModel 
from .serializer import DatasetSerializer 

class DatasetView(generics.ListCreateAPIView):
    queryset = DatasetModel.objects.all() 
    serializer_class = DatasetSerializer

    def get_queryset(self):
        return self.queryset.filter(owner=self.request.user)

Upvotes: 1

Related Questions