Incorrect String Value Error When Saving Unicode Characters in MySQL with Django
When attempting to save unicode strings to the auth_user model in Django, you may encounter the following error message:
Incorrect string value: '\xC4\x8Dius' for column 'last_name' at row 104
Potential Causes
This error is typically caused by the following:
Solution
To resolve this issue, follow these steps:
Change the database, table, and columns to use the utf8mb4 character set:
CREATE DATABASE db_name CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';
ALTER TABLE auth_user CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
Specify the character set in Django settings:
In the Django settings file (settings.py), add the following line:
DATABASES = { 'default': { 'ENGINE':'django.db.backends.mysql', ... 'OPTIONS': {'charset': 'utf8mb4'}, } }
Additional Considerations
The above is the detailed content of How to Fix \'Incorrect String Value\' Errors When Saving Unicode in Django and MySQL?. For more information, please follow other related articles on the PHP Chinese website!