Home > Blockchain >  Django rest framework : creating a user ask for authentication
Django rest framework : creating a user ask for authentication

Time:10-27

I was using django user, authentication and permission modules but while making a request to create a new user in the POST request, its asking for authentication.

enter image description here

and I am getting

{
    "detail": "Authentication credentials were not provided."
}

Here is my serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'password']

        extra_kwargs = {
            'password' : {
                'write_only':True,
                'required': True
            }
        }
    
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        Token.objects.create(user=user) # create token for the user
        return user

    def update(self, instance, validated_data):
        instance.username = validated_data['username']
        instance.set_password(validated_data['password'])
        instance.save()

        return instance

views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    permission_classes = [IsAuthenticated, IsOwnerOfObject]
    authentication_classes = (TokenAuthentication,)

urls.py

from django.urls import path, include
from .views import UserViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('users', UserViewSet, basename = 'users')

urlpatterns = [
    path('api/', include(router.urls)), 
]

CodePudding user response:

It's because permission_classes you set include IsAuthenticated. If you want to make it public with user creation like below example code, then custom Permission class has to be implemented that allows it.


class CustomizedUserPermission(IsAuthenticated):
    def has_permission(self, request, view):
        if view.action == 'create':
            return True
        return super().has_permission(request, view)  
      
class UserViewSet(viewsets.ModelViewSet):
    ...
    permission_classes = [CustomizedUserPermission, ]

updated to override get_permissions class in ViewSet


class UserViewSet(viewsets.ModelViewSet):
    def get_permissions(self): 
        if self.request.action == 'create': 
                return [] 
        return super().get_permissions()

  • Related