mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-03 12:00:12 +03:00
feat: easier to extend the payload returning the token without having to repeat code
This commit is contained in:
parent
522d453546
commit
e667e03c99
|
@ -205,7 +205,17 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
|
||||
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by inheriting from `ObtainAuthToken` and overriding the `get_data` function, and using that in your url conf instead.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
class CustomAuthToken(ObtainAuthToken):
|
||||
|
||||
def get_data(self, user, token, created):
|
||||
return {'token': token.key, 'user_id': user.pk}
|
||||
|
||||
```
|
||||
|
||||
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
and include them using the `throttle_classes` attribute.
|
||||
|
|
|
@ -12,13 +12,17 @@ class ObtainAuthToken(APIView):
|
|||
renderer_classes = (renderers.JSONRenderer,)
|
||||
serializer_class = AuthTokenSerializer
|
||||
|
||||
def get_data(self, user, token, created):
|
||||
return {'token': token.key}
|
||||
|
||||
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)
|
||||
return Response({'token': token.key})
|
||||
data = self.get_data(user, token, created)
|
||||
return Response(data)
|
||||
|
||||
|
||||
obtain_auth_token = ObtainAuthToken.as_view()
|
||||
|
|
Loading…
Reference in New Issue
Block a user