Search code examples
pythonpython-3.xdjangodjango-viewsglobal-variables

How to store Global variable in Django view


In Django views, is it possible to create a global / session variable and assign some value (say, sent through an Ajax call) in a view and make use of it in another view?

The scenario I'm trying to implement will be something like:

View view1 gets some variable data sent thru' Ajax call:

def view1(request):
    my_global_value = request.GET.get("data1", '') # Storing data globally

Then, the stored variable is used in another view, view2:

def view2(request):
    my_int_value = my_global_value # Using the global variable

Solution

  • Create a variable in the views.py (outside of a function) like this preferably using all CAPS

    GLOBAL_VAR_X = ''    # Global var
    

    Then pass the value to be stored to the global like this:

    def view1(request):
        # Using "global" to declare it in the function where data is being received and to be passed
        global GLOBAL_VAR_X
        GLOBAL_VAR_X = request.GET.get("data1", '') # Storing data globally
    

    Then, the stored variable is used in another view

    def view2(request):
        my_int_value = GLOBAL_VAR_X # Using the data stored in the global variable "GLOBAL_VAR_X"
        print(str(my_int_value))    # Will print the value in the terminal