'SessionStore'对象没有属性'email'

时间:2022-08-26 07:57:26

I'm struggling to access my session variable in django.

我正在努力在django中访问我的会话变量。

I have two different apps custom_user and article. in my views.py file of custom_user i have declared a session variable.

我有两个不同的应用程序custom_user和文章。在我的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')

and in my views.py of article app I'm accessing it like this.

在我的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})

my articles.html file inherits base.html file and there i'm using {{loggedin}} to access the variable. I have used {{request.session.email}} but this also doesn't work

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

What I ultimately want to do is to show the email address of the user loggedin throughout my site in my navbar which is in base.html file.

我最终想要做的是在我的导航栏中显示在我的站点中登录的用户的电子邮件地址,该地址位于base.html文件中。

I'm only getting the user.email value in loggedin.html file which is rendered in auth_view function. but not in any other html file.

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

1 个解决方案

#1


You should be accessing it as:

你应该访问它:

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

...in the same way you've defined it.

......就像你定义它一样。

Also, to prevent an error in the case that it's not set, you can use:

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

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

Read more about using session variables in views in the docs.

阅读有关在文档中的视图中使用会话变量的更多信息。

#1


You should be accessing it as:

你应该访问它:

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

...in the same way you've defined it.

......就像你定义它一样。

Also, to prevent an error in the case that it's not set, you can use:

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

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

Read more about using session variables in views in the docs.

阅读有关在文档中的视图中使用会话变量的更多信息。