1

I am trying to receive context data in django template and work with it in javascript. Currently i am receiving the data but as a string and it looks gibberish.

my code:

{% extends "base.html" %}

{% block content %}
    {% if search_list %}
        <!-- do something -->
    {% endif %}

    <!-- javascript code  -->

    {% block script %}
    <script >
        let data = '{{search_list}}'
        
        console.log(data);
        
    </script>
    {% endblock script %}
   

{% endblock %}

and views.py

from django.shortcuts import render
from .models import search_history


def index(request):
    search_list = search_history.objects.order_by('-query_date')[:10]
    context = {'search_list': search_list}
    return render(request, 'search_history/index.html', context)

If i remove the quote in the variable search_list in javascript it shows me error. i have used jsonify and safe tag it doesn't work. How do i get the data as an object here?

dak baksho
  • 13
  • 4
  • It's a template and `{{search_list}}` will be evaluated at html generation time. Thus everything inside can be nothing but static text/string. If you want object - parse it the way you'd parse a response to AJAX request. e.g. `JSON.parse()` – Ivan Starostin Mar 26 '21 at 18:11
  • There is no `receive` there is _substitution of placeholders_. – Ivan Starostin Mar 26 '21 at 18:12
  • @IvanStarostin I have tried parsing the data to JSON but it doesn't work. in the above code the line **let data = '{{search_list}}'** logs something like this in the console : ```<QuerySet [<search_history: whats the meaning of life>, <search_history: how to search``` – dak baksho Mar 27 '21 at 16:52
  • @IvanStarostin `{{search_list}}` without the quote gives this error - `Uncaught SyntaxError: Unexpected token '&'` – dak baksho Mar 27 '21 at 16:58
  • Add your view code. – Ivan Starostin Mar 27 '21 at 17:36
  • @IvanStarostin added – dak baksho Mar 27 '21 at 18:24
  • same question https://stackoverflow.com/questions/3345076/django-parse-json-in-my-template-using-javascript – Ivan Starostin Mar 27 '21 at 18:45

1 Answers1

1

Return data as JSON

import json

def index(request):
    search_list = search_history.objects.order_by('-query_date')[:10]
    context = {'search_list': json.dumps(search_list)}
    return render(request, 'search_history/index.html', context)

get it in js

let data = JSON.parse("{{ search_list | escapejs }}");

or

let data = {{ search_list | safe }};

And consider turning all this into more elegant way:

  • ajax request
  • json response

however making ajax request is somewhat complicated, requires manual csrf sending and so on, but you won't have to render big constant json values in the final html.

The view for json response and the original view would look like then:

def index(request):
    return render(request, 'search_history/index.html')

def get_search_list(request):
    search_list = search_history.objects.order_by('-query_date')[:10]
    return JsonResponse({'search_list': search_list})
Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39