将Python Social Auth用户名传递给View

时间:2015-09-15 10:43:39

标签: python django

用户可以使用Python Social Auth

登录Facebook

我已经确认可以在我的某个模板中使用此数据来获取Facebook数据

{% if user and not user.is_anonymous %}
   <p class="navbar-text"><a href="/recommendations/{{user.username}}">{{ user.username }}!</a></p>
   <p class="navbar-text"><a href="/logout">Logout</a></p>
{% else %}
<a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}"><button type="button" class="btn btn-default navbar-btn">Sign in with Facebook</button></a>
{% endif %}

但是当我尝试在如下的视图中调用user.username时,它会返回错误。

def personalised(user):
    return HttpResponse(user.username)

错误:

'WSGIRequest' object has no attribute 'username'

我相信这来自我的urls.py设置

来自django.conf.urls导入模式,url,include 来自soundshelterapp导入视图

urlpatterns = patterns('soundshelterapp.views',
    url(r'^$', views.home, name='home'),
    url(r'^personalised$', views.personalised, name='name'),
    url(r'^social/', include('social.apps.django_app.urls', namespace='social')),
    url(r'^login/$', 'login',name='login'),
    url(r'^logout/$', 'logout',name='logout')
    )

2 个答案:

答案 0 :(得分:2)

您正在混合上下文变量和Django视图。 personalised是Django视图,其参数是request对象,而不是user

您在模板中获得的{{user}}是因为django.contrib.auth.context_processors.auth在表示当前登录用户的上下文中添加了user变量。由于用户已登录,因此request.user属性将设置为已登录用户,然后您可以使用username访问request.user.username

def personalised(request): # request object is passed to a view
    username = request.user.username # get the username of logged-in user
    return HttpResponse(username) # return response

答案 1 :(得分:1)

我已经习惯了如何获得usernme

def personalised(request):
    current_user = request.user