Django user first_name is not required but has NOT NULL constraint in database


In my Django project I would like to have nullable User's first and last name. Django documentation say that last_name and first_name fields are optional. However when I want to insert values to auth_user table via SQL without first_name and last_name I got an error of not-null constraint

auth_user(id, password, last_login, is_superuser, username, email, is_staff, is_active, date_joined)
(8, 'secret', null, false, 'user5', '', false, true, current_date);

ERROR:  null value in column "first_name" violates not-null constraint

I am using:

  • Django 1.10 (upgraded from django 1.9 during project development)
  • Postgresql 9.6 (upgraded from pg 9.5 during project development)
  • django.contrib.auth.User

By django admin site it is possible to create User without providing first_name and last_name.

Could you please help me to know why there is such a mismatch and how can I insert via SQL User with empty first and last name?

Show source
| database   | django   | postgresql   2016-12-30 15:12 1 Answers

Answers ( 1 )

  1. 2016-12-30 16:12

    Why are you using raw SQL for this rather than the Django ORM, out of curiosity?

    It's not actually defined as NOT_NULL, it's defined as optional/blank when you're using the ORM (and consquently, forms). It's defined as this in the library:

    first_name = models.CharField(_('first name'), max_length=30, blank=True)

    In other words, you can pass it as blank in forms, but it still has a NOT_NULL constraint. If you were doing it in the ORM, you wouldn't notice this, as it defaults to an empty string, per this answer. So your options are either to pass it an empty string in your SQL query, or to use the ORM:

    u = User.objects.create(your_stuff_here)
◀ Go back