作为回应,我只获得发布数据的可读字段。我也希望返回主键和用户名。
serializers.py:
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'full_name', 'email','password',)
extra_kwargs = {
'password':
{
'write_only': True,
'required': False
}
}
read_only_fields = ('username',)
views.py:
class UserCreate(UserMixin, generics.CreateAPIView):
serializer_class = UserCreateSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
if serializer.is_valid():
User.objects.create_user(**serializer.validated_data)
email = serializer.validated_data.get('email', None)
password = serializer.validated_data.get('password', None)
user = authenticate(email=email, password=password)
login(request, user)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
return Response({
'status': 'Bad request',
'message': 'Account could not be created with received data.'
}, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:1)
两件事。您希望在返回之前保存用户,因为PK是在保存时生成的。您还想序列化用户对象,而不是返回POST数据。所以在你的create()结束时你需要像
这样的东西... user.save() response_data = UserCreateSerializer(user).data return Response(response_data, status...
那就是说,您确定要自动登录新创建的用户吗?看起来很奇怪。
答案 1 :(得分:0)
User.objects.create_user()
返回用户模型的实例。你想用它来获得主键:
user = User.objects.create_user(**serializer.validated_data)
user.save()
pk = user.pk
你需要自己调用save()告诉django它现在应该保留,否则这将在以后完成。
查看django docs以获取更多信息。