开发者

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

开发者 https://www.devze.com 2022-12-19 10:37 出处:网络
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 l

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 rang开发者_C百科e(128), HTTP response headers must be in US-ASCII format ...


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!


django way:

from django.http import HttpResponseRedirect
from django.utils.http import urlquote

return HttpResponseRedirect(u'/page/?title=%s' % urlquote(query_string))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号