mbanayosi
mbanayosi

Reputation: 23

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

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.

Upvotes: 1

Views: 2765

Answers (2)

hyounis
hyounis

Reputation: 4579

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

Upvotes: 2

Hedde van der Heide
Hedde van der Heide

Reputation: 22449

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

Upvotes: 0

Related Questions