我的DRF后端有一个有效的注册API。我希望能够通过PUT请求对用户个人资料进行更新。如何编写验证用户并用匹配ID更新用户的方法?我还想编写一个方法来处理DELETE请求,并删除ID匹配请求的用户。
# serializers.py
class RegisterSerializer(ModelSerializer):
class Meta:
model = User
fields = (
'account_type',
'id',
'username',
'name',
'email',
'phone',
'country',
'city',
'adress_1',
'adress_2',
'zip_code',
'photo',
'password',
)
...
def create(self, validated_data):
user = super(RegisterSerializer, self).create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
# api.py
class RegisterAPI(CreateAPIView):
permission_classes = (AllowAny,)
serializer_class = RegisterSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
token = Token.objects.create(user=serializer.instance)
token_data = {"token": token.key}
return Response({
"token": token.key,
"user": {**serializer.data}
})
# urls.py
urlpatterns = [
...
path('api/auth/register', RegisterAPI.as_view()),
...
]
答案 0 :(得分:0)
您可以阅读有关put
方法的更详细信息in the docs
def put(self, request, pk, format=None):
user = self.get_object(pk)
serializer = UserSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)