【问题标题】:'SessionStore' object has no attribute 'email''SessionStore' 对象没有属性 'email'
【发布时间】:2015-05-11 15:08:24
【问题描述】:

我很难在 django 中访问我的会话变量。

我有两个不同的应用程序 custom_user 和 article。 在我的 custom_user 的 views.py 文件中,我声明了一个会话变量。

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:
        auth.login(request, user)
        request.session['email'] = user.email
        return render_to_response(request, "loggedin.html", locals(),context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/accounts/invalid')

在我的文章应用程序的views.py中,我正在像这样访问它。

def articles(request):

    return render_to_response('articles.html',
        {'articles':Article.objects.all().order_by('-id'),'last':Article.objects.earliest('-pub_date'), 'loggedin':request.session.email})

我的articles.html 文件继承了base.html 文件,我使用{{loggedin}} 来访问该变量。 我用过 {{request.session.email}} 但这也不起作用

我最终想要做的是在 base.html 文件中的导航栏中显示登录整个网站的用户的电子邮件地址。

我只在 auth_view 函数中呈现的 loggedin.html 文件中获取 user.email 值。但不在任何其他 html 文件中。

【问题讨论】:

    标签: python django session session-storage sessionstorage


    【解决方案1】:

    您应该以以下方式访问它:

    'loggedin': request.session['email']
    

    ...以您定义它的相同方式。

    另外,为了防止在未设置的情况下出错,您可以使用:

    'loggedin': request.session.get('email')
    

    阅读更多关于在视图中使用会话变量in the docs

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 2019-05-03
      • 2021-06-12
      • 2016-09-22
      • 1970-01-01
      • 2018-11-18
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多