Unicode in python with Django and MongoEngine

I am trying to compare two strings, the first, s1, from mongoengine, and the second, s2, comes from a Django HTTP request.

They look like this:

>>> s1 = product_model.Product.objects.get(pk=1).name
>>> s1
u'Product \xe4 asdf'
>>> s2 = request.POST['name']
>>> s2
'Product \xc3\xa4 asdf'

They have the same letter in them: "ä", but mongoengines (s1) is in the Unicode string of Python, and Djangos (s2) is in the Python byte sequence with Unicode encoded characters.

I can easily solve this, for example. convert Python unicode string to byte string

>>> s1.encode('utf-8') == s2
True

But I would like to think that the best practice is that all my Python strings are encoded the same on my system, right?

How can I tell Django to use Python Unicode strings? Or how can I tell MongoEngine to use unicode encoded Python byte bytes?

+4
1

Django docs :

, Django - , , - - : . Unicode, ( "bytestrings" ), UTF-8.

Python 3 , Unicode, -, "b". Django 1.5 unicode_literals . , bytestring, "b".

Python 2:

my_string = "This is a bytestring"
my_unicode = u"This is an Unicode string"

Python 2 Unicode Python 3:

from __future__ import unicode_literals

my_string = b"This is a bytestring"
my_unicode = "This is an Unicode string"

Python 2, . :

. (farmdev.com/talks/unicode) " , Unicode , " . Django , unicode, Django, . : s1 == s2.decode( "utf8" ), Unicode

, .

EDIT: , Django HttpRequest, :

HttpRequest.encoding

, ( None, DEFAULT_CHARSET). , . (, GET POST) . , DEFAULT_CHARSET.

+2

All Articles