Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

458
Views
Passing a Dictionary from Django view to a Django template

I am trying to pass the following context from views.py to a Django Template:

views.py:

def home(request):
     context = {
           'dict_1': {'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']} 
          }
return render(request, 'app/home.html', context)

home.html:

<script type="text/javascript">
    var java_dict = {{ dict_1 }};
    console.log(java_dict);
</script>

This throws an error: Uncaught SyntaxError: Unexpected token '&'

Upon investigating, I see that the dictionary in javascript is read as follows:

{&#39;key_1&#39;: [&#39;val_11&#39;, &#39;val_12&#39;], &#39;key_2&#39;: [&#39;val_21&#39;, &#39;val_22&#39;]}

which probably means that the quotes-character (') is read incorrectly. How do I fix this issue?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The context data that you pass into Django templates are escaped by default, for security purposes.

If you're sure that the data is safe, you can do this:

views.py

import json

def home(request):
    # Use JSON dump so that it will be a data that can be loaded in javascript
    context = {
        'dict_1': json.dumps({
            'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']
        })
    }
return render(request, 'app/home.html', context)

home.html

<script type="text/javascript">
    var java_dict = {{ dict_1| safe }};  // Actually solve your problem. Don't escape the data.
    console.log(java_dict);
</script>
about 4 years ago · Juan Pablo Isaza Report

0

By default, all values in Django templates escape HTML characters for security purposes. If you want to use this dictionary in JavaScript you should use json_script filter. Please read the docs to understand what's going on.

A solution for your problem would be to:

  1. Add the script tag containing your dict to the template

    {{ dict_1 |json_script:"ID_OF_NEW_SCRIPT_TAG" }}
    
  2. Load the dict value in your script tag (I'll use the name you had in your example)

    var java_dict = JSON.parse(document.getElementById('ID_OF_NEW_SCRIPT_TAG').textContent);
    
    console.log(java_dict);
    

Replace ID_OF_NEW_SCRIPT_TAG with whatever ID makes sense to you.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!