Django Rest -创建用户密码哈希

lx0bsm1f  于 2023-01-10  发布在  Go
关注(0)|答案(2)|浏览(105)

我试图哈希密码,一旦创建用户和我使用Django Rest。但是,我得到了一个错误时,试图创建它。

{
    "non_field_errors": [
        "Invalid data. Expected a dictionary, but got str."
    ]
}
    • 一米一米一**
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'active',
                  'admin', 'date_joined', 'password', 'partner']
    • 一米二米一x**
class UserViewset(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.DjangoFilterBackend,)

    def create(self, request, *args, **kwargs):
        user = User.objects.all()
        serializer = UserSerializer(
            user, make_password(request.data['password']))
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
        # return HttpResponse(user)

先谢了...

f2uvfpb9

f2uvfpb91#

啊我找到了答案xD

class UserViewset(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = (filters.DjangoFilterBackend,)

    def perform_create(self, serializer):
        # Hash password but passwords are not required
        if ('password' in self.request.data):
            password = make_password(self.request.data['password'])
            serializer.save(password=password)
        else:
            serializer.save()

    def perform_update(self, serializer):
        # Hash password but passwords are not required
        if ('password' in self.request.data):
            password = make_password(self.request.data['password'])
            serializer.save(password=password)
        else:
            serializer.save()
vwkv1x7d

vwkv1x7d2#

def create(self, request, *args, **kwargs):
    self.request.data['password'] = make_password(self.request.data['password'])
    serializer = self.serializer_class(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response({'message': 'Usuario creado correctamente!'}, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

相关问题