Reputation: 23
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?
Upvotes: 2
Views: 3194
Reputation: 9299
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:
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})
Upvotes: 1