title: How to pass a queryset from django to javascript function?
body: <p>I want to pass a queryset from a view to a javascript function throught the template:</p>
  
  <p>my <code>view.py</code>:</p>
  
  <pre><code>def myview(request):    
      lista=Mymodel.objects.filter(tipo=mytipo)
      context_dict['lista']=lista
      return render(request, 'mytemplate.html', context_dict)
  </code></pre>
  
  <p>my <code>template.html</code>:</p>
  
  <pre><code>  &lt;script&gt;
    &lt;!--
      window.onpageshow = function() {
        myfunction('{{lista}}');
      };
    --&gt;
    &lt;/script&gt;
  </code></pre>
  
  <p>my <code>javascript.js</code>:</p>
  
  <pre><code>function myfunction(lista) {
    for (i=0; i&lt;lista.length; i++) {
                console.log(lista[i].name)
    }
  }
  </code></pre>
  
  <p>The problem is that <code>lista</code> become a string. I tried with JSONEncoder but i'm not sure how to use. I would like to avoid JsonResponse because I want to use that view for my template (if possible).</p>
  
  <p><strong>Edit:</strong> </p>
  
  <p>There's a problem with the solution proposed in the answer: </p>
  
  <pre><code>TypeError: Python object is not JSON serializable
  </code></pre>
  
  <p>and the solution proposed in <a href="https://stackoverflow.com/questions/36555602/typeerror-python-object-is-not-json-serializable">this link</a> doesn't works either (can't find <code>_meta</code> attribute called by <code>model_to_dict</code>).</p>
  
  <p>JSON.parse doesn't works</p>
  
  <pre><code>SyntaxError: missing ) after argument list
  </code></pre>
  
  <p>and the problem seem to be between one path and the other: </p>
  
  <pre><code>myfunction(JSON.parse('['/mypath/myimage.png', '/otherpath/otherimage.png', 'etc... ']'));
  </code></pre>
  
  <p>Also in the template you must add <code>|safe</code>.</p>
  
  <p>Luckly I need a list of string so:</p>
  
  <p>my <code>view.py</code>:</p>
  
  <pre><code>def myview(request):    
      lista=Mymodel.objects.filter(tipo=mytipo)
      lista_formatted=[]
      for elem in lista:
          lista_formatted.append('/media/'+str(elem.myfield))
      lista_formatted=json.dumps(lista_formatted)
      context_dict['lista']=lista_formatted
      return render(request, 'mytemplate.html', context_dict)
  </code></pre>
  
  <p>my <code>template.html</code>:</p>
  
  <pre><code>  &lt;script&gt;
    &lt;!--
      window.onpageshow = function() {
        myfunction({{lista|safe}});
      };
    --&gt;
    &lt;/script&gt;
  </code></pre>