Django - Session variables does not change unless the page is refreshed

淺唱寂寞╮ 提交于 2021-02-08 06:38:38

问题


I am using a session variable to check whether the user is logged in as a contractor or an employer

When contractor :

request.session['LoggedAsContractor'] = True

When employer :

request.session['LoggedAsContractor'] = False

I then implemented two switch methods, toContractor & toEmployer, that simply changes the session variable.

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.

This error does not happen when running the project on the localhost, it only happens when the project is deployed (Gondor).

This is the type of session I have :

INSTALLED_APPS = (
'django.contrib.sessions',
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
)

UPDATE

This is the method toContractor which is called by the button 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'])

The difference between request.session['LoggedAsContractor'] = True and request.session['LoggedAsContractor'] = False, is the view in the HTML.

The HTML code :

{% if request.session.LoggedAsContractor %}
    <!-- Show some buttons -->
{% else %}
    <!-- Show other buttons -->
{% endif %}

UPDATE 2

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 %}

the url /contractor/username/switch/ redirects to the method switchToEmployer.

the url /employer/username/switch/ redirects to the method switchToContractor.


回答1:


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



回答2:


That's not an error any request needs a response to display something to the user. Can you add your button function?



来源:https://stackoverflow.com/questions/11776523/django-session-variables-does-not-change-unless-the-page-is-refreshed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!