Serg
Serg

Reputation: 99

Django Request.GET and Unicode

How can I decode value from request.GET if it in unicode?

def find_streets(request, qs=None):
    city_name = request.GET.get('city_name')
    print(request.GET.get('city_name'))
    # %u041C%u043E%u0441%u043A%u0432%u0430
    # (Москва)
    qs = models.Streets.objects.values_list('street_name', flat=True).filter(city__city_name=city_name)

If I filtering english word - I successfully get results, but if I filter russian word - result is empty. For example, russian word Москва returns from request.GET in unicode as:

%u041C%u043E%u0441%u043A%u0432%u0430

Encoding this to utf-8 returns the same value.

How to convert %u041C%u043E%u0441%u043A%u0432%u0430 into Москва or how to filter DB data using this unicode value?

Upvotes: 0

Views: 720

Answers (2)

Essex
Essex

Reputation: 6138

As suggested in this post: here

You could use urllib like this exemple:

a = b'restaurant_type=caf\xc3\xa9'
urllib.parse.parse_qs(a.decode())
# > {'restaurant_type': ['café']}

In your case, it could be:

def find_streets(request, qs=None):
    city_name_tmp = request.GET.get('city_name')
    city_name = urllib.parse.parse_qs(city_name.decode())
    qs = models.Streets.objects.values_list('street_name', flat=True).filter(city__city_name=city_name)

Could you try and give me the result ?

Upvotes: 0

Serg
Serg

Reputation: 99

Sorry. Problem was not in Python but in my JS code (escape() function). I replaced it with encodeURI().

ex. var url = "find_streets?city_name=" + encodeURI(cityName);

Upvotes: 1

Related Questions