Django-除非刷新页面,否则会话变量不会更改 [英] Django - Session variables does not change unless the page is refreshed
问题描述
我正在使用会话变量来检查用户是以承包商还是雇主
I am using a session variable to check whether the user is logged in as a contractor or an employer
承包商时:
request.session['LoggedAsContractor'] = True
当雇主时:
request.session['LoggedAsContractor'] = False
然后,我实现了两种转换方法,即转译给承包商和toEmployer,只需更改会话变量即可.
I then implemented two switch methods, toContractor & toEmployer, that simply changes the session variable.
在HTML视图中,当我单击切换"按钮时,该变量不会更改,并且没有其他更改,但是在刷新页面时,该变量也会更改,并且其他所有内容.
From the HTML view, when I click the switch button, the variable does not change and nothing else changes, but when I refresh the page, the variable changes and everything else.
在本地主机上运行项目时不会发生此错误,只有在部署项目(Gondor)时才会发生.
这是我参加的会议的类型:
This is the type of session I have :
INSTALLED_APPS = (
'django.contrib.sessions',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
)
更新
这是 toContractor 方法,由 Switch
def switchToContractor(request, user_name):
request.session['LoggedAsContractor'] = True
if "employer" in request.GET['next']:
if str(request.user) == user_name:
return redirect('/contractor/' + user_name + '/')
else:
return redirect(request.GET['next'])
else:
return redirect(request.GET['next'])
request.session ['LoggedAsContractor'] = True 和 request.session ['LoggedAsContractor'] = False 之间的区别是HTML中的视图.
The difference between request.session['LoggedAsContractor'] = True and request.session['LoggedAsContractor'] = False, is the view in the HTML.
HTML代码:
{% if request.session.LoggedAsContractor %}
<!-- Show some buttons -->
{% else %}
<!-- Show other buttons -->
{% endif %}
更新2
这是包含切换"按钮的HTML代码:
This is the HTML code that contains the Switch button :
{% if request.session.LoggedAsContractor %}
<a href="/contractor/{{request.user}}/switch/?next={{request.path}}">Switch to Employer View</a>
{% else %}
<a href="/employer/{{request.user}}/switch/?next={{request.path}}">Switch to Contractor View</a>
{% endif %}
URL /contractor/username/switch/重定向到方法 switchToEmployer .
the url /contractor/username/switch/ redirects to the method switchToEmployer.
URL /employer/username/switch/重定向到方法 switchToContractor .
the url /employer/username/switch/ redirects to the method switchToContractor.
推荐答案
代替重定向,您应该使用更新的会话来呈现响应.例如:
Instead of redirecting, you should instead render a response with the updated session. For example:
def my_example(request):
request.session['key'] = True
response = render_to_response("example.html", context_instance = RequestContext( request ), mimetype = "text/html" )
return response
这篇关于Django-除非刷新页面,否则会话变量不会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!