views:

257

answers:

2

How to redirect to a query string URL containing non-ascii characters in DJANGO?

When I use "return HttpResponseRedirect(u'/page/?title=' + query_string)" where the query_string contains characters like "你好", I get an error "'ascii' codec can't encode characters in position 21-26: ordinal not in range(128), HTTP response headers must be in US-ASCII format" ...

A: 
HttpResponseRedirect(((u'/page/?title=' + query_string).encode('utf-8'))

is the first thing to try (since UTF8 is the only popular encoding that can handle all Unicode characters). That should definitely get rid of the exception you're observing -- the issue then moves to ensuring the handler for /page can properly deal with UTF-8 encoded queries (presumably by decoding them back into Unicode). However, that part is not, strictly speaking, germane to this specific question you're asking!

Alex Martelli
the chinese character is '\xe4\xbd\xa0' in utf-8... '\xe4', in integer form is "228"... which can't be converted to ascii because its out of range(128). :/ I remember there's a form of representation like 由 or something like that, but I can't find any information on it.There's a post somewhere that makes a passing reference to it: http://forums.mysql.com/read.php?103,22136,22199#msg-22199
Eric
@Eric, when you pass a `str` (an encoded byte string) to `HttpResponseRedirect`, rather than a `unicode` object as you did, there will be no need for Python to try to encode it (with the default `'ascii'` codec) and fail. So the `\xe4` (and other characters of ord >= 128) will not be a problem!
Alex Martelli
OMG I've found the answer, after so many hours... HttpResponseRedirect(urllib.quote_plus((u'/page/?title=' + query_string).encode('utf-8')))
Eric
Thanks heaps !!
Eric
+1  A: 

django way:

from django.utils.http import urlquote
HttpResponseRedirect(u'/page/?title=%s' % urlquote(query_string))
slav0nic