Django REST Framework+Social Django集成Google OAuth2遇AttributeError
问题根源
这个报错是因为命名冲突+social-django对DRF环境的适配问题:
- 代码里误把
requests库的Request类当成了Django的HttpRequest来用,而前者根本没有login属性; - social-django原本是给Django传统web视图设计的,默认依赖session认证,DRF的请求对象结构和传统Django请求不一样,直接套用会出问题。
修复步骤
排查导入冲突
检查所有涉及请求处理的文件,避免把requests的Request和Django的请求对象搞混:# 错误写法,会引发命名冲突 from requests import Request # 正确导入Django请求对象 from django.http import HttpRequest安装DRF适配扩展
social-django有专门的DRF适配包,直接安装:pip install social-auth-app-django[django-rest-framework]更新settings配置
在settings.py里补全DRF相关的认证配置:INSTALLED_APPS = [ # 原有应用 'rest_framework', 'social_django', 'social_django_rest_framework', # 新增DRF适配应用 ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'social_django_rest_framework.authentication.SocialAuthentication', # 新增social认证类 ], } # Google OAuth2基础配置 SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '你的Google客户端ID' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '你的Google客户端密钥' SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email', 'profile']替换回调视图为DRF适配版
把原来的回调路由换成social-django提供的DRF专用视图:from social_django_rest_framework.views import SocialAuthCompleteView urlpatterns = [ # 其他路由 path('social-auth/complete/google-oauth2/', SocialAuthCompleteView.as_view(), name='socialauth_complete'), ]更新依赖并重启服务
pip install --upgrade social-auth-app-django requests python manage.py runserver
内容的提问来源于stack exchange,提问作者Stanislav Felshtyn
相关产品推荐
相关产品推荐

