How to update Django session variable in javascript

0 votes
I want to update a Django session variable following a Javascript event (well, actually jQuery).

Do I need to do this via a POST request?

Or can Javascript and Django share session variables in some clever way, in which case can I update the session variables direct from jQuery?
Jul 30, 2020 in Python by kartik
• 37,520 points
7,030 views

1 answer to this question.

0 votes

Hello @kartik,

You can do this via Ajax. You'll need a simple Django view that updates the session variable, which the jQuery will call:

def update_session(request):
    if not request.is_ajax() or not request.method=='POST':
        return HttpResponseNotAllowed(['POST'])

    request.session['mykey'] = 'myvalue'
    return HttpResponse('ok')

and the JS:

$.post('/update_session/', function(data) {
    alert(data);
});

Hope it helps!!

To know more about Java, join our Java course online today.

Thank You!!

answered Jul 30, 2020 by Niroj
• 82,840 points

Related Questions In Python

0 votes
1 answer

How to update date automatically after a value change in django?

Hello @kartik, Only change your pub_date if published has ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,840 points
9,728 views
0 votes
1 answer

How to look up a dictionary value with a variable in Django template?

Hii @kartik, Write a custom template filter: from django.template.defaulttags ...READ MORE

answered Aug 3, 2020 in Python by Niroj
• 82,840 points
10,747 views
0 votes
1 answer

How to expire session due to inactivity in Django?

Hello @kartik, Expire the session on browser close ...READ MORE

answered Aug 13, 2020 in Python by Niroj
• 82,840 points
10,370 views
0 votes
1 answer

How to strip html/javascript from text input in django?

Hello @kartik, Django provides an utility function to ...READ MORE

answered Aug 17, 2020 in Python by Niroj
• 82,840 points
1,905 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,509 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,586 views
0 votes
1 answer

How to use Django variable in JavaScript file?

Hello @kartik, You need to print it before ...READ MORE

answered Jul 29, 2020 in Python by Niroj
• 82,840 points
14,520 views
0 votes
1 answer

How to update user password in Django Rest Framework?

Hello @kartik, Using a modelserializer might be an ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,840 points
9,291 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP