0

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)), 
]
Himanshu Poddar
  • 7,112
  • 10
  • 47
  • 93
  • i think you are having the same problem with [here](https://stackoverflow.com/questions/26906630/django-rest-framework-authentication-credentials-were-not-provided). Hope it helps – aberkb Oct 26 '21 at 15:41
  • my question is different because I am using viewsets along with the user model of django to create the user – Himanshu Poddar Oct 26 '21 at 15:43

1 Answers1

1

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.action == 'create': 
                return [] 
        return super().get_permissions()

Donghyun Lee
  • 166
  • 3