1

I'm sending an array from a django view to an html (in which there is a JS script) but the array seems to be a string. In fact if I try to console.log(array[0]) or console.log(array[1]) it returns in the first case [ and in the second case '

The code is:

Django view

def results(request):
   h = request.POST['h']   
   name = request.POST['name']

   array = [h, name]
return render(request, 'app/index.html', {'h':h, 'array':array})

index.html

<script>
   var h = "{{ h }}"   //this is 3 
   var array = "{{ array|safe }}"  //this is ['3', 'John']
   console.log(h)
   console.log(array[0])
   console.log(array[1])

The console is:

3 

[

'

I wish it was:

3

3

John

Do you have any idea how can I access the n value of the array? Thanks

4
  • 2
    Could you try remove quotes.So, can you use {{ array|safe }} instead of "{{ array|safe }}"? Commented Mar 3, 2020 at 10:18
  • No! It is mandatory for calling variable from django view, without quotes it doesn't even compile anymore Commented Mar 3, 2020 at 10:20
  • 2
    I think it is not, could you try it? Commented Mar 3, 2020 at 10:24
  • I tried, the code editor was giving me an error, but at the end I ran the code and it worked! Thank you so much Commented Mar 3, 2020 at 11:21

2 Answers 2

1

You can use {{ array|safe }} instead of "{{ array|safe }}" withouth any extensions.

Sign up to request clarification or add additional context in comments.

Comments

0

Try the package django-jsonify

pip install django-jsonify

Then add jsonify to django INSTALLED_APPS

In your template

{% load jsonify %}

var array = {{ array|jsonify }}

Hope this helps you, if any thing please let me know.

2 Comments

If I use this approach I got two errors: Uncaught SyntaxError: Unexpected string (at the line of var array) Uncaught ReferenceError: h is not defined (at the line I will use h)
try removing the double quotes var array = {{ array|jsonify }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.