用于创建用户的POST请求工作正常,但是当我在用户上执行PUT方法并更改密码时我得到Invalid password format or unknown hashing algorithm
,所以我有点困惑为什么会发生这种情况,所以有人可以帮助我克服这一点。
MyUserSerializer
from rest_framework import serializers
from business_accounts.models.my_user import MyUser
class MyUserSerializer(serializers.ModelSerializer):
"""
TODO: MyUser model Serializers
:return: TODO
"""
password = serializers.CharField(min_length=8, write_only=True)
class Meta:
model = MyUser
fields = '__all__'
def create(self, validated_data):
user = super(MyUserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
用户详细的APIView
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from ..serializers.my_user_serializers import MyUserSerializer
from business_accounts.models.my_user import MyUser
class UserDetailView(APIView):
"""
User detail api view
"""
def get_object(self, pk):
try:
return MyUser.objects.get(pk=pk)
except MyUser.DoesNotExist:
raise Http404
def get(self, request, pk):
user = self.get_object(pk)
serializer = MyUserSerializer(user)
return Response(serializer.data)
def put(self, request, pk):
user = self.get_object(pk)
serializer = MyUserSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
user = self.get_object(pk)
user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
答案 0 :(得分:2)
您需要使用散列算法。 检查 - > this
答案 1 :(得分:0)
您还需要覆盖序列化程序的update
方法,以正确设置PUT请求的密码:
class MyUserSerializer(serializers.ModelSerializer):
"""
TODO: MyUser model Serializers
:return: TODO
"""
password = serializers.CharField(min_length=8, write_only=True)
class Meta:
model = MyUser
fields = '__all__'
def create(self, validated_data):
user = super(MyUserSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
password = validated_data.pop('password')
user = super(MyUserSerializer, self).update(instance, validated_data)
if password:
user.set_password(password)
user.save()
return user
注意set_password
方法用于密码哈希。