4

Trying:

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 first or last name is foreign accented letters (unicode?) I get garbage in the user's record.

What can I do?

user967722
  • 1,213
  • 1
  • 20
  • 26

2 Answers2

3

Django supports unicode strings for User model, but also your database must support it. If you're using sqlite there must not be a problem, but for example in mySQL, default column encoding is not utf-8.

To solve the problem, you can manually change the auth_user table columns first_name and last_name collation to utf8_unicode_ci. Alternatively you can set database collation to utf8_unicode_ci before doing syncdb (and creating tables for the fist time), this way all your tables and columns follow same encoding.

Amir Ali Akbari
  • 5,973
  • 5
  • 35
  • 47
1

Amir is correct.

To change the MySQL collation of and existing table you could 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 non-empty.

odedfos
  • 4,491
  • 3
  • 30
  • 42