Python Django简单用户会话

Python Django简单用户会话,python,django,templates,session,Python,Django,Templates,Session,我只需要一个简单的django用户会话身份验证。登录、用户数据、注销。还可以在模板中测试会话。代码: def auth_view(request): username = request.POST.get('username','') password = request.POST.get('password','') user = auth.authenticate(username = username, password = password) if us

我只需要一个简单的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')
def auth_视图(请求):
username=request.POST.get('username','')
password=request.POST.get('password','')
user=auth.authenticate(用户名=用户名,密码=密码)
如果用户不是无:
如果user.u处于活动状态:
身份验证登录(请求、用户)
返回HttpResponseRedirect(“/accounts/loggedin”)
其他:
返回HttpResponseRedirect(“/accounts/auth_view”)
其他:
返回HttpResponseRedirect(“/accounts/invalid”)
def loggedin(请求):

request.session['username']=request.user.username/(尝试了这个)因此,正如人们所建议的,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))

遗漏了一个重要部分:问题是什么?实际上没有。我只需要代码方面的帮助。这是对代码的请求。:)既然在
request.user
对象中已有用户名,为什么需要将其存储在会话dict中?为什么不直接在模板中使用
user
对象呢?因为我无法从模板访问它。我尝试用我的_data={}响应base.html。但它只有在我处于那种特定的视角时才起作用。在php中,我使用会话对用户进行身份验证,这很简单。我无法用django python来理解它。我无法理解django中的用户身份验证,我已经研究了所有文档。但是,如果您是通过相同的父对象访问会话dict,则随机将内容插入会话dict没有任何帮助—
请求
——您将使用用户名。当然,问题是您首先没有向模板发送
请求<代码>呈现(请求、模板名称、上下文)
将为您完成此操作,请参见。不要使用
呈现到响应
。使用后,您将免费获得RequestContext。完成后,您将一直在那里。告诉过你这只适用于一个视图。将该上下文发送到模板的视图。其他URL的情况--->其他视图不起作用。我知道我不需要在django auth中为用户使用会话。如果有办法,请向我解释,然后做我需要的事情。当然,在应用程序的所有视图中都无法返回此信息。这太愚蠢了。也许问题在于模板。如何解决这个问题?这可能是这篇文章的正确问题。
def your_view(request):
    return render_to_response('my_template.html', context_instance=RequestContext(request))