ozo
ozo

Reputation: 943

Django - Get the first and last names of an user

When a user is created, one can add the first and last name in the user's profile.

My question is: how can I access this information? If I only wanted the username I would do it with user.get_username. How should I access first name and last name?

Upvotes: 3

Views: 2174

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

A User [Django-doc] object has a .first_name [Django-doc] and .last_name [Django-doc] attribute as well.

So for a user u, you can fetch:

the_first_name = u.first_name
the_last_name = u.last_name

Note that both can empty, and these are not required to be unique.

You can also access what Django defines as the "full name" with .get_full_name() [Django-doc]. In that case Django joins the .first_name and the .last_name together, with a space in the middle.

In fact these fields and functions are defined in the AbstractUser [Django-doc] model, as you can see in the source code [GitHub]. In case you customize the user model, it is possible that those fields no longer exist.

Upvotes: 2

Related Questions