Penny Chen
Penny Chen

Reputation: 79

How to use the context variables passed from Django in javascript? Already changed to Json type

I want to make a table in HTML by using javascript. Now I'm done with the header and displayed correctly. Now I would like to add the content in the table by adding from the database. However, once I declare the context variable from the view.py I created, the table will disappear. How can I call the data correctly from the view.py I made into javascript? I knew it should be JSON style. How can I fix it? thanks in advance.

views.py

@csrf_exempt
def test(request):
    return render(request, 'test.html')

def testJS_page(request):
    context_list = {}

    customers = Customer.objects.all()
    carts = Cart.objects.all().select_related('customer').order_by('customer_id')
    goods = Good.objects.select_related('cart__customer').order_by('cart_id')

    context_list['Cart'] = carts
    context_list['Good'] = goods
    context_list['Customer'] = customers
    context = {"Customer_status": json.dumps(context_list)}

    return render(request, 'test.html', context)

test.js

var customer_status = ({{ Customer_status|safe }});

function createTable() {

  var myTableDiv = document.getElementById("myDynamicTable");
  var table = document.createElement('TABLE');
  var thread = document.createElement('THREAD');
  thread.className = "thead-dark";

  table.appendChild(thread);
  var tr1 = document.createElement('TR');
  thread.appendChild(tr1);
  var th1 = document.createElement('TH');
  var th2 = document.createElement('TH');
  var th3 = document.createElement('TH');
  var th4 = document.createElement('TH');
  th1.appendChild(document.createTextNode("Product"));
  th2.appendChild(document.createTextNode("Count"));
  th3.appendChild(document.createTextNode("Price"));
  th4.appendChild(document.createTextNode("Subtotal"));
  tr1.appendChild(th1);
  tr1.appendChild(th2);
  tr1.appendChild(th3);
  tr1.appendChild(th4);

  myTableDiv.appendChild(table);
}
createTable();

once I write the code "var customer_status = ({{ Customer_status|safe }});", It seems going wrong.

Upvotes: 0

Views: 63

Answers (1)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

We can not use context variables in .js files. We can only use them in .html files.


But you can do something like this in your .html file:

<script>
  var customer_status = JSON.parse("{{ Customer_status|safe }}");
</script>

And then use customer_status["Good"] in your .js files.

Upvotes: 2

Related Questions