How to Create a Session Variable in Django



Python


In this article, we show how to create a session variable in Django.

A session variable is useful because it retains its value across multiple web pages. So even if a user clicks on an anchor tag and goes to another page on your site, the value of that session variable remains. This is the importance of session variables.

As long as there are no major changes, such as a user logging in or logging out, the value of a session variable remains intact.

Thus, there are many uses for session variables for a website.

So in order to create a session variable in Django, we use the following code shown below.



So in order to create a session variable, we use the term, request.session[]

Inside of this request.session[] variable, we place the name of the session variable. In the above case, it is 'username'. We then set this username session variable to the value of 'David'.

And you can do this for any number of session variables in Django.

To display this session variable in a template file, we use the following code shown below.



Thus, now we can display the session variable in a template file, if needed.

Again, the value of session variables is that once created and the session remains intact (no logins or logouts), the value of the session variable remains throughout all pages in the site and can be referenced through all pages of the site (all the template pages as well as all the view.py pages where we execute our Python code).

Using sessions have values anywhere where you want to track a user throughout the site until the session gets destroyed (such as through a logout).

And this is how you can create a session variable in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...