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