【发布时间】:2013-11-26 02:38:10
【问题描述】:
我只想要一个简单的 django 用户会话身份验证。登录,用户数据,注销。还可以在模板中测试会话。代码:
def auth_view(request):
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username = username, password = password)
if user is not None:
if user.is_active:
auth.login(request,user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/auth_view')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
request.session['username'] = request.user.username //( tried this)<----------
return render_to_response('loggedin.html',
{ 'username' : request.user.username})
def logout(request):
auth.logout(request)
(kill the session) <-----------
return render_to_response('logout.html')
基本模板(所有模板都扩展了这个): ...
<div id="rightsidebar">
{% block rightsidebar %}
{% if request.session.username != Null %} // (tried this) <-----------
Loggedin
{% else %}
Not Loggedin
{% endif %}
{% endblock %}
</div>
<div id="content">
{% block content %}This is the content area{% endblock %}
...
【问题讨论】:
-
遗漏了一个重要部分:问题是什么?
-
其实没有。我只是想要代码方面的帮助。它是对代码的请求。 :)
-
当
request.user对象中已经存在用户名时,为什么还需要将用户名存储在会话字典中?为什么不直接在模板中使用user对象? -
因为我无法从模板访问它。我尝试用 my_data = {} 响应 base.html。但它仅在我处于该特定视图时才有效。在 php 中,我曾经使用会话对用户进行身份验证,这很简单。我无法在 django python 中弄清楚。我无法理解 django 中的用户身份验证,我研究了所有文档。
-
但是,如果您通过与用户名相同的父对象 -
request访问它,则将内容随机插入会话字典并没有帮助。当然,问题在于您一开始没有将request发送到模板。render(request, template_name, context)会为您完成这项工作,请参阅 the docs。
标签: python django templates session