我是Django和DRF的新手,我试图通过POST请求创建新用户。我发送了用户名和密码参数,但是django没有识别POST请求中的参数。
我的序列化器:
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user=get_user_model().objects.create(
username = validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = get_user_model()
fields = ('username', 'password')
我的观点类:
class CreateUserView(CreateAPIView):
model = get_user_model()
permission_classes = (AllowAny,)
serializer_class = UserSerializer
我曾尝试使用serializers.ModelSerializer和serializer.Serializers但没有成功。
答案 0 :(得分:0)
class UserSerializer(serializers.ModelSerializer):
def create(self, validated_data):
user = UserModel.objects.create_user(**validated_data)
return user
class Meta:
model = YOUR_MODEL
fields = ('username', 'password',)
class CreateUserView(CreateAPIView):
model = YOUR_MODEL.objects.all()
permission_classes = (AllowAny,)
serializer_class = UserSerializer
您可以这样查看并检查错误。
class CreateUser(APIView):
permission_classes = (AllowAny,)
def post(self, request):
post_data = request.data
print post_data # See what is your post DATA
serializer = UserSerializer(data=post_data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(data={'user':serializer.data})
return Response(data={'user':serializer.errors})