Django Chinese Error

Source: Internet
Author: User

Django view functions often encounter errors similar to 'ascii 'codec can't decode byte 0xef in position 0: ordinal not in range (128.

Before resolving the error, you must first understand the difference between Unicode and UTF-8.

Unicode refers to a world code table ". UTF-8 is the encoding method stored in this code table. Unicode does not have to be compiled into bytecode storage by UTF-8. You can also use other methods such as UTF-16 and utf-7. At present, most of them are converted to bytecode in UTF-8 mode.

In python, the string types are byte string and Unicode string.

If the encoding method specified in the python file is UTF-8 (# Coding = UTF-8), all Chinese strings will be considered UTF-8 encoded byte strings (for example: mystr = "hello"), but the string generated in the function is considered Unicode string

This is where the problem occurs. Unicode string and byte string cannot be used in combination. Once used in combination, this error will occur. For example:

Self. response. Out. Write ("hello" + self. Request. Get ("argu "))

Here, "hello" is considered a byte string, while the return value of self. Request. Get ("argu") is considered Unicode string. Because the preset decoder is ASCII, the Chinese byte string cannot be recognized. Then an error is reported.

There are two solutions:

1. Convert all strings into byte strings.

Self. response. Out. Write ("hello" + self. Request. Get ("argu"). encode ("UTF-8 "))

2. Convert all strings to Unicode strings.

Self. response. Out. Write (U "hello" + self. Request. Get ("argu "))

Byte string can be converted to Unicode string (unicodestring, "UTF-8 ")

Django Chinese Error

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.