从Cookie获取用户名

时间:2011-01-08 18:11:58

标签: python django web django-views

我使用django的后端解决方案。我只想从cookie或session_key获取用户名以了解用户。我怎么能这样做?

from django.contrib.auth.models import User
from django.contrib.sessions.models import Session

def start(request, template_name="registration/my_account.html"):
    user_id = request.session.get('session_key')
    if user_id:
        name = request.user.username
        return render_to_response(template_name, locals())
    else:
        return render_to_response('account/noauth.html')

只有其他人才会出现。我做错了什么?

我是否正确,经过身份验证意味着他已登录?

- >好的,我得到了! 首先,如果您对问题有一些澄清,请更新问题,不要像您所做的那样发布答案或(甚至更糟)另一个问题。其次,如果用户退出,根据定义他没有用户名。

我的意思是Cookies的优势在于再次识别用户。我只是想把他的名字放在网页上。即使他退出了。或者这不可能吗?

3 个答案:

答案 0 :(得分:4)

您可以通过调用名为is_authenticated的方法来检查用户是否已通过身份验证。您的代码看起来会像这样:

def start(request, template_name="registration/my_account.html"):
    if request.user.is_authenticated():
        name = request.user.username
        return render_to_response(template_name, locals())
    else:
        return render_to_response('account/noauth.html')

无需自己访问会话,Django会自动处理所有这些内容(假设您同时使用django.contrib.sessionsdjango.contrib.auth)。

/ edit:为了拥有用户的用户名,他需要进行身份验证。没有好办法。

答案 1 :(得分:2)

piquadrat绝对是正确的答案,但如果由于某种原因你确实需要让会话中的用户,你在会话对象上调用get_decoded()

session_data = request.session.get_decoded()
user_id = session_data['_auth_user_id']

答案 2 :(得分:0)

您需要在settings.py的MIDDLEWARE_CLASSES设置中启用AuthenticationMiddleware和SessionMiddleware,才能在您的视图中访问 request.user

http://docs.djangoproject.com/en/1.2/topics/auth/#authentication-in-web-requests

然后,您可以使用 request.user.username

访问用户名