1

I am facing some problems trying to access a context variable in my django views in my html javascript. I would like to access 'unclean' context which is a list and USE IT AS A LIST in my html script tag. Any help is appreciated. Thank you. Below are some of my code:

views.py

context = { 
  'unclean' : unclean
       }
2
  • Have you tried to use {{ unclean }}? Commented Dec 30, 2019 at 3:24
  • Yes. However, accessing the variable like this in javascript makes it a 'string' type. I need to use it as an 'array' type in javascript for manipulation. Thanks for the help. Commented Dec 30, 2019 at 3:27

2 Answers 2

0

You can use the json_script tag to include a python object as a JS variable in your template

{{ unclean|json_script:"unclean-data" }}

<script>
    var unclean = JSON.parse(document.getElementById('unclean-data').textContent);
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Here is a demo of latest version, which is similar to your case.

python code

from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

HTML code:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

2 Comments

I did not downvote, I was just going through the review queues as someone else has flagged your post as low quality (link only). To prevent this from happening again, I recommend reading the How do I write a good answer help page.
Thank you! Still I cannot agree that someone else did that, he could write his answer or just remind me. It's a quite simple question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.