Save Unicode first_name & last_name to Django user record

Attempt:

new_user = User.objects.create_user(username, email, password) new_user.first_name = first_name new_user.last_name = last_name new_user.save() 

but if the first or last name is letters with foreign letters (unicode?), I get garbage in the user record.

What can I do?

+4
source share
2 answers

Django supports unicode strings for the User model, but your database must also support it. If you use sqlite, there should be no problems, but, for example, in mySQL, the default column encoding is not utf-8.

To solve this problem, you can manually modify the auth_user first_name and last_name column tables for utf8_unicode_ci . Alternatively, you can set the database mapping to utf8_unicode_ci before doing syncdb (and creating tables in the first time), so all your tables and columns follow the same coding.

+3
source

Amir is right.

To change the MySQL collation and the existing table, you can do:

 > python manage.py dbshell mysql> mysql> ALTER TABLE auth_user -> DEFAULT CHARACTER SET utf8mb4, -> MODIFY first_name CHAR(30) -> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, -> MODIFY last_name CHAR(30) -> CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL; Query OK, 10 rows affected (0.35 sec) Records: 10 Duplicates: 0 Warnings: 0 

This can be done even if the table is not empty.

+1
source

All Articles