从 Cookie 中获取用户名
我在用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')
我只得到了其他的结果。我哪里做错了?
那么,认证的意思就是他已经登录了吗?
--> 好的,我明白了!首先,如果你对某个问题有疑问,应该更新这个问题,而不是发一个答案或者(更糟糕的是)再问一个新问题,像你刚才那样。其次,如果用户已经登出,根据定义他就没有用户名。
我的意思是,cookie的好处就是可以再次识别用户。我只是想在网页上显示他的名字。即使他已经登出,也可以做到吗?
3 个回答
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来获取用户名了。
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.sessions
和 django.contrib.auth
)。
/编辑:要获取用户的用户名,用户必须先登录。没有什么好的方法可以绕过这一点。
2
piquadrat的回答是完全正确的,但如果出于某种原因你需要从会话中获取用户信息,你可以在会话对象上调用 get_decoded()
方法:
session_data = request.session.get_decoded()
user_id = session_data['_auth_user_id']