Better alternative for passing complex object from template to views.py on POST call

Question:

In views.py on GET call, I create a random list of questions (its a complex object, list of dictionaries) and I send that list to the template (HTML) file using return render(request, 'some_page.html', args).

I show one question at a time and once user enters the answer and clicks next, the next question is shown and so on.
On every ‘next’ click, the answer has to be stored back in the database.

What are my options on how can I send the answer to the backend while directing the user to the next question?
An important thing to note here is that once that list of questions is generated, I cannot generate it again. I have to either save that list somewhere for this instance or pass it to and from views.py and template on every call. I think passing the list on every call is not an ideal solution and looking for a better suggestion. I show the questions in HTML one by one and there is a current index variable which i managed using JS.

This is what the end of my GET function in views.py looks like:

    final_data = [very, complicatedly, ordered, list]
    final_data = json.dumps(final_data)    
    args = {"data":final_data}
    return render(request, 'index.html', args)
Asked By: Umer Tariq

||

Answers:

My answer: I’d just use Ajax (javascript), btn click -> post -> success + next question


Per the json.dumps() in the render, easier to show blocks:

If you are just using Django template code like {{data.0}} and

<!-- `i` being the question text -->
{% for i in data %}
  <div id="question_{{ forloop.counter }}" hidden>{{i}}</div>
{% endfor %}

You do not need to do the json.dumps()

The only time I can see the need for a json.dumps() is if you are immediately piping the value in Javascript, like

<html>
  <head>
    <title> Example </title>

    <script>
      myComplicatedList = JSON.parse('{{data}}');
    </script>

  </head>
</html

You would need to in this case so you could translate a Python Array into a Javascript Array.

I’m not sure how you are using data in the templates, but I thought I’d just throw it out there.

Side Note: Idk if 1 method of storing data is better. I personally like the hidden Divs, instead of Javascript Vars, but it does come with the added risk of user’s finding & changing them (low probability in my uses)

Answered By: Nealium