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?