django休息框架 - 添加到views.obtain_auth_token [英] django rest framework - adding to views.obtain_auth_token

查看:1195
本文介绍了django休息框架 - 添加到views.obtain_auth_token的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用django休息框架实现了令牌身份验证,我可以将用户名和密码发送到 / api-token-auth / 并获取令牌。

  url(r'^ api-token-auth /',token_views.obtain_auth_token)

除了令牌之外,我想要获得与返回的令牌相关的 User 对象。



如何覆盖/添加此视图并返回实际的User对象?

解决方案

您可以在这里找到相关视图:



https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authtoken/views.py#L21



假设您已经创建了一些用户序列化程序,您基本上可以使用用户在那里实例,并将其推入您的UserSerializer。然后将其添加到响应中,如下所示。

  ... 
user_serializer = UserSerializer(user)
返回响应({'token':token .key,'user':user_serializer.data}


I have implemented Token Authentication with django rest framework and I can post username and password to /api-token-auth/ and get the token.

url(r'^api-token-auth/', token_views.obtain_auth_token)

In addition to the token, I want to get the User object related to the returned token.

How can I override/add to this view and also return the actual User object?

解决方案

You can find the relevant view here:

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authtoken/views.py#L21

Assuming you've created some sort of User serializer already, you can basically take the user instance there and shove it into your UserSerializer. then add it to the response, something like the below.

... 
user_serializer = UserSerializer(user)
return Response({'token': token.key, 'user': user_serializer.data})

这篇关于django休息框架 - 添加到views.obtain_auth_token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆