Set a Session Variable

A snippet showing how to set session variables in Django.


# views.py

def set_session(request):
    request.session['username'] = 'ahmad'
    return HttpResponse("Session set!")
      
Explanation:
  • Use request.session['key'] = 'value' to set a session variable.
  • Stores 'username' in the session for the logged-in user.
  • Category Sessions & Cookies
  • Total Views 948
  • Last Modified 19 May, 2026
  • Tags #sessions #set #request #django
Previous snippet
Custom Log Formatter
Next snippet
Get a Session Variable
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.