0

I am first passing a JS variable 'confirmed' to my Django view via POST request. I then run a python script which takes this variable and does some processing. Finally I want to pass it back to my html/JS so I can display the processed data.

I am currently trying to use Django sessions to achieve my goal but there is a '1 session delay', so the session variable which I update is returning as the value from the previous session.

Is there a better way I can pass the variable from my view to JS/a fix for my current solution?

VIEW:

def crossword(request):
    if request.method == 'POST':
        Session.objects.all().delete()

        str_squares = (request.body).decode('utf-8')
        squares = [int(i) for i in str_squares.split(',')]

        letters = puzzle_solver.solve_puzzle(3, squares)
        # print(letters)
        for each_square in letters.keys():
            request.session[each_square] = letters[each_square]

        request.session.modified = True

    return render(request, 'crossword.html')

JS:

            // Output a list of active squares
            var xhr = new XMLHttpRequest();

            var generate = { Generate:function(){ 
                var confirmed = [];
                for (i=0; i<active_boxes.length; i++){
                    confirmed.push(active_boxes[ i ].id_num);
                }
                console.log(confirmed);

                xhr.open("POST", "http://localhost:8000/", true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.send(c=confirmed);

                console.log("{{ request.session.keys }}")
                console.log("{{ request.session.values }}")
                var tester = parse_session_keys("{{ request.session.keys }}");

                console.log(tester);
                solve_crossword(tester);
             }};
Joeyboy
  • 432
  • 4
  • 16

1 Answers1

1

Is there a reason why you are not sending the response directly back to JS? In your views.py, you can do

from django.http import JsonResponse

def crossword(request):
    if request.method == 'POST':
        str_squares = (request.body).decode('utf-8')
        squares = [int(i) for i in str_squares.split(',')]
        letters = puzzle_solver.solve_puzzle(3, squares)

        return JsonResponse(letters)

    return render(request, 'crossword.html')

After sending your request, wait and read the response directly as JSON then play with it in your JS code, as described in this post.

If there is any reason preventing you from doing this (for example there might be a form also makes POST requests to the same page thus you need to eventually land on rendering the crossword template), allocate another url for your api like /api/crossword

Your original idea of using session should not be used in this use case, especially with your Session.objects.all().delete() line (don't delete all session data without checking).

Foocli
  • 157
  • 1
  • 11