-1

我只想要一个简单的 django 用户会话 auth 。登录,用户数据,注销。还可以在模板中测试会话。代码:

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 %}

...

4

1 回答 1

0

因此,正如人们所建议的那样,Django 身份验证已经内置,您不需要 sessionstate。正如您所描述的,您应该能够通过您的 base.html 页面访问您的登录用户。

在您的模板中

{% if user.is_authenticated %}
user is logged in
{% else %}
user is NOT logged in
{% endif %}

您需要确保您遇到问题的所有视图都在使用 RequestContext

在你看来

def your_view(request):
    return render_to_response('my_template.html', context_instance=RequestContext(request))
于 2013-11-13T14:23:16.950 回答