作爲迴應,我只獲取發佈數據的可讀字段。我想要返回主鍵和用戶名。在Django rest框架中發佈數據後如何返回主鍵作爲響應?
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)
我認爲看到你的UserCreateSerializer代碼會告訴服務返回什麼可能會有幫助。 – themanatuf
更新了代碼。對不起,以前沒有提及。 –