【问题标题】:Django simple user sessionDjango 简单用户会话
【发布时间】: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


【解决方案1】:

正如人们所建议的那样,Django 身份验证已经内置,您不需要会话状态。正如您所描述的,您应该能够通过您的 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))

【讨论】:

  • 不要使用render_to_response。使用render,您将免费获得RequestContext。
  • 做到了,去过那里。告诉你这只适用于一种观点。将该上下文发送到模板的视图。其他网址的情况---> 其他视图不起作用。我知道我不需要在 django auth 中为用户使用会话。如果有办法,请向我解释,做我需要的。当然,没有办法在应用程序的所有视图中返回它。它只是愚蠢的。也许问题出在模板上。如何解决?这可能是这篇文章的正确问题。
猜你喜欢
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2011-08-25
  • 2015-12-04
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2017-02-02
相关资源
最近更新 更多