How to store Global variable in Django view

Question:

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
Asked By: Love Putin Not War

||

Answers:

You can use Session Django Docs

Some example from Django:

def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    c.save()
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

Edit the MIDDLEWARE setting and make sure it contains
'django.contrib.sessions.middleware.SessionMiddleware'

Your request.session.get("key") is also accessible in any other view.

Answered By: NKSM

You can use Sessions, but you better delete it after you’ve done with it. Otherwise, it will persist with the session.

def index(request):
    task_created = ""
    if 'task_created' in request.session:
        task_created = request.session['task_created']
        del request.session['task_created']
    ...


def create_task(request):
    ...
    request.session['task_created'] = "ok"
    return redirect('index')
Answered By: Wariored

You can use the global variable as shown below:

my_global_value = None # Here

def view1(request):
    global my_global_value # Here

    my_global_value = request.GET.get("data1", '')
    # ...

def view2(request):
    global my_global_value # Here

    my_int_value = my_global_value
    # ...
Answered By: Kai – Kazuya Ito

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
Answered By: Love Putin Not War