Alex
Alex

Reputation: 625

Django user model custom fields names

How to rename fields of the user model?

I want to rename the fields

first_name to firstName, last_name to lastName with AbstractUser

class User(AbstractUser):
    email = models.EmailField('email address',unique=True)
    firstName = models.CharField("First Name", max_length=150)
    lastName = models.CharField("Last Name", max_length=150)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [
        'username',
        'firstName',
        'lastName',
    ]

The above code works, but it does not rename the fields what it does is add the fields firstName and lastName

Any ideas or suggestions?

Upvotes: 1

Views: 947

Answers (2)

Benyamin Jafari
Benyamin Jafari

Reputation: 34026

You can simply override the respective field in the inherited class and create a new field with a new name instead if you really don't want to use any alias name or db_column as Barney Szabolcs mentioned.

Therefore, we can override first_name and last_name with ' ' to avoid any exception error as they've been used in other areas — admin field_sets, get_full_name method, etc. Or you can also override them as well.

class User(AbstractUser):
    email = models.EmailField('email address', unique=True)
    first_name = ' '
    last_name = ' '
    firstName = models.CharField('First name', max_length=150)
    lastName = models.CharField('Last name', max_length=150)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [
        'username',
        'firstName',
        'lastName',
    ]

Note that you must add the following line in the settings.py:

AUTH_USER_MODEL = '<respective-app-name>.User'

Moreover, to ensure that you can check the created migration file content.

Upvotes: -1

Barney Szabolcs
Barney Szabolcs

Reputation: 12514

I think you could use the db_column parameter, so you can hopefully override AbstractUser's default fields.

class User(AbstractUser):
    email = models.EmailField('email address',unique=True)
    first_name = models.CharField("First Name", db_column="firstName", max_length=150)
    last_name = models.CharField("Last Name", db_column="lastName", max_length=150)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [
        'username',
        'firstName',
        'lastName',
    ]

With reference to the documentation: https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.Field.db_column

Upvotes: 1

Related Questions