jax
jax

Reputation: 4197

How can I transfer context variable into a html bound javascript code in Django?

I have write down a view:

def Country_names(request):
    c_list = []
    for c_name in c_names:
        c_list.append(c_name)
    return render(request, 'DATAPLO/Country_list.html', {'c_list':c_list})

This view transfers a list/array to template further in my html template it try to convert this python variable into javascript array variable.

<script>
//variable defined to store "c_list" array 
 var c_names = {{c_list}}
//try to access array items like this
 c_names[0]
</script>

But his method is not working in my case how can I do this, I have explore dfew similar threads on the web but nothing is working in my case.

thanks

Upvotes: 0

Views: 221

Answers (2)

Updated answer which includes a Country model

models.py:

class Country(models.Model)
    name = models.CharField(max_length=100)

So if your country model looks like this, we need to make that into a list of strings to be converted to json.

import json

def Country_names(request):
    c_list = Country.objects.all().values_list('name', flat=True)
    return render(request, 'DATAPLO/Country_list.html', {'c_list':json.dumps(c_list)})

And then output in HTML. Remember to mark it safe, so it doesn't get escaped

<script>
    //variable defined to store "c_list" array
    var c_names = {{c_list|safe}}
</script>

Upvotes: 1

badiya
badiya

Reputation: 2257

You can use values_list() to get the list of country names.

import json
def getCountryNames(request):
    country_names = list(Country.objects.values_list('name', flat=True))
    return render(request, 'DATAPLO/Country_list.html', {'country_names':json.dumps(country_names)})

rest is same as @Sune's answer

Upvotes: 0

Related Questions