创建您自己的自定义令牌获取视图,如下所示,
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
class TokenObtainView(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
custom_response = {
'token': token.key,
'user_id': user.id
}
return Response(custom_response)
然后把你的TokenObtainView
班级连接到你的urls.py
urlpatterns = [
# other patterns
path('path/to/your/custom/token/view/', views.TokenObtainView.as_view(), name='new-token,obtain-view')
]
现在开始,您应该使用端点path/to/your/custom/token/view/
来获取您的自定义响应。