Django rest-auth注册。使用 token 认证时如何通过 key 返回user_id

标签 django django-rest-framework django-registration

我正在使用Djando rest_auth.registration。

我在urls.py中的相应条目是

url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))

我的身份验证类是rest_framework.authentication.TokenAuthentication

其余的API调用效果很好。

通过此API注册时,会收到以下响应。
{
  "key": "3735f13cd69051579156f98ffda338a2d7a89bb5"
}

我也想在响应中包含user_id字段。我该怎么做。我尝试从类 RegisterView(CreateAPIView)扩展方法 get_response_data :但是无法这样做。有人可以建议实现此目标的最佳做法。代码将是理想的。谢谢。

我想使用rest_auth.registration开箱即用提供的rest-auth/registration/url。我不想为此创建一个单独的新URL。

我的Settings.py如下
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'sdAPI.apps.SdapiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_framework_swagger',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django_extensions',
]

# auth and allauth settings
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
    'SCOPE': ['email', 'publish_stream'],
    'METHOD': 'oauth2'  # instead of 'oauth2'
    }
}

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
    ),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
)
}

SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 
REST_SESSION_LOGIN = False

我的urls.py如下
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/',include('rest_auth.registration.urls')),
]

最佳答案

我认为您只需要在TOKEN_SERIALIZER配置中覆盖REST_AUTH_SERIALIZERS选项即可。

from rest_framework.authtoken.models import Token

class TokenSerializer(serializers.ModelSerializer):

    class Meta:
        model = Token
        fields = ('key', 'user')

然后,按照文档所示在settings.py中进行设置,
REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
    'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
    ...
}

关于Django rest-auth注册。使用 token 认证时如何通过 key 返回user_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44965908/

相关文章:

python - 将一个休息资源路由为第二个休息资源的子资源

django - 在 Django Admin 中为 token 部分添加搜索字段

django - 如何在 Django REST Swagger 中生成响应消息列表?

json - Django 无法解析内部服务器错误的 WSGIRequest 的 POST 参数

Python电子邮件lib message_from_bytes函数错误

python - 使用 ChoiceField 时出现 Django Rest API TypeError

python - 如何在 Django 注册表中添加额外的字段?

python - 在 Django 中扩展表单?

django-registration create_user() 意外关键字

python - 如何在 Django 之外访问 Django DB 和 ORM