django1.6.11 html文件獲取session數據

本版本 django 1.6.11
關於session
views.py中爲session賦值,

request.session['is_login'] = True
request.session['user_id'] = user.id
request.session['user_name'] = user.name

在html文件中獲取session爲空:

{{request.session.user_name}}

結果爲空
解決方法

1 在訪問的頁面前獲取session值,並將值傳遞給html模板:

user_name = request.session.get('user_name', None)  
return render_to_response('login/index.html', {'user_name': user_name})

在html模板通過

{{user_name}}

可獲取用戶名

2 修改django配置文件setting.py

添加如下:

TEMPLATE_CONTEXT_PROCESSORS = (

    "django.contrib.auth.context_processors.auth",

    "django.core.context_processors.debug",

    "django.core.context_processors.i18n",

    "django.core.context_processors.media",

    "django.core.context_processors.static",

    "django.core.context_processors.tz",

    "django.contrib.messages.context_processors.messages",

    "django.core.context_processors.request",

)

在html模板中通過

{{request.session.user_name}}

可獲取session中key=user_name對應值
類似與views.py中

user_name = request.session.get('user_name', None) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章