Django rest 框架:创建用户要求进行身份验证

Django rest framework : creating a user ask for authentication

我正在使用 Django 用户、身份验证和权限模块,但是在 POST 请求中请求创建新用户时,它要求进行身份验证。

我得到

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

这是我的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)), 
]

这是因为 permission_classes 您设置了包含 IsAuthenticated。如果你想像下面的示例代码那样通过用户创建来实现 public,那么必须实现允许它的自定义权限 class。


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, ]

已更新以覆盖 ViewSet

中的 get_permissions class

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