在DRF中,我有一些自定义操作可以对用户建模。用户实例都处于 is_active = False 的状态。我试图制作能够将用户转为的内容is_active = True 。我为我的用户模型制作了一个具有OneToOne的令牌模型。我试图制作的函数是:如果用户放入表单的令牌等于user.token,则设置 user.is_active = True 。我很困惑如何做到这一点。我创建了自己的序列化程序类:
class ActivateUserSerializer(serializers.ModelSerializer):
phonenumber = serializers.CharField()
token = serializers.CharField()
class Meta:
model = UserProfile
fields = ['phonenumber','token']
def get_token(self, obj):
request = self.context.get('request')
x = request.data['phonenumber']
obj = UserProfile.objects.get(phonenumber=x)
if request.data['token'] == obj.first_token:
obj.is_active = True
obj.save()
我知道这不是.create()。或update()函数。这就是我到目前为止的方式。我不知道我应该使用什么视图来实现这个功能。
答案 0 :(得分:0)
您可以在API中创建新的POST端点以获取此自定义操作,例如:
api/users/<phone number>/activate
然后,在视图类中,您可以实现操作:
from rest_framework import status, viewsets
from rest_framework.decorators import detail_route
from rest_framework.response import Response
class UserView(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
# Use your own user serializer
serializer_class = UserSerializer
@detail_route(methods=['post', ])
def activate(self, request, phonenumber):
obj = UserProfile.objects.get(phonenumber=phonenumber)
# The POST request expects a token
if not request.data['token']:
return Response({'message': 'Token not provided'},
status=status.HTTP_400_BAD_REQUEST)
# Compare the token
elif request.data['token'] == obj.first_token:
obj.is_active = True
obj.save()
return Response({'message': 'User activated'})
# Maybe you could add an error code if you need
return Response({'message': 'User not activated'})