[Answered ]-Prevent rendering the unicode character in django template

1👍

As mentioned in the docs fetchall returns a list of tuples, so each of the country name is inside a tuple in the list. You need to flatten the list to get list of countries.

countries = cur.fetchall()
countries = [c[0] for c in countries]
ctx['countries'] = countries

1👍

I’m assuming you’re using Python2.

From the documentation, here’s what you would get after calling json.dumps:

>>> json.dumps([(u'Abyei',), (u'Afghanistan',)])
'[["Abyei"], ["Afghanistan"]]'

Since you get a single JSON formatted string serialized from dictionary, when you iterate it, you’ll get a character on every iteration. This explains why you get single characters when you render the data.

Your countries is already a dictionary thus can be used without serializing; if you want to convert unicode strings, you can do something like:

>>> countries = [(u'Abyei',), (u'Afghanistan',)]
>>> [(country.encode('ascii','ignore'), ) for (country, ) in countries]
[('Abyei',), ('Afghanistan',)]

Leave a comment