Home > OS >  Passing a Dictionary from Django view to a Django template
Passing a Dictionary from Django view to a Django template

Time:03-31

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?

CodePudding user response:

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.

CodePudding user response:

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>
  • Related