Why is python / django returning a unicode list after split()

I have a form in Django with a TextField that receives comma separated input e.g. test1,test2,test3,test4, which is then split like such:

test = request.POST.get('test', '').split(',')

then saved to a Postgres database model

and then retrieved and displayed

When displayed however, the returned split list is in unicode,

[u'test1', u'test2', u'test3', u'test4']

instead of the desired

['test1', 'test2', 'test3', 'test4']

Why is this? The problem with this is I can't figure out how to display each element of the array in a django template page - the regular

{% for element in list %}
    <p>{{ element }}</p>
{% endfor %}

isn't working. Any thoughts?


Django uses Unicode wherever it can by default. In general this is a good thing.

The reason you are getting Unicode strings is the get() method is returning a Unicode string that you are splitting.

This should not be a problem - Django will accept and handle Unicode strings everywhere as you would expect it to. In fact, the Django docs linked above recommend going Python 3.x style and making Unicode the default string:

As we are doing in Django code from version 1.5, we recommend that you import unicode_literals from the __future__ library in your code. Then, when you specifically want to create a bytestring literal, prefix the string with ‘b’.

Your loop should work exactly as expected.

Need Your Help

php jquery contact form without using mail()

php contact-form

I've been trying to follow a tutorial to make a contact form - http://www.tutwow.com/htmlcss/create-a-simple-and-secure-contact-form-with-jquery-and-php/