0

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

1
  • The script should be inside the HTML, not in a separate .js file. Works pretty well if it's inside the HTML page. Commented Jul 19, 2017 at 6:29

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

6 Comments

showing strange error: TypeError at /DATAPLO/ <QuerySet [<Country: India>, <Country: pakistan>]> is not JSON serializable.
Ahh ok, so you then we need a list comprehension after all. I will update the answer
@ Sune can you explain what did we use "country.name " during list comprehensions
A better approach would be to use values_list if all you need is just names
I'm not sure I understand your question, but basically what we did during the list comprehension is to loop over all the countries and add their name property to a new list
|
0

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

Comments

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.