Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the first name and last name of a logged in user in Django?

I need to get the first name and last name of a user for a function in my views How do I do that? What is the syntax for it? I used request.user.email for the email, but I don't know see an option for a first name or last name. How do I go about doing this?

Should I import the model into the views and then use it?

like image 304
DeA Avatar asked Feb 09 '17 03:02

DeA


2 Answers

There are multiple ways to get the information you require.

  • request.user.get_full_name(), returns the first name and last name, separated by a space.

  • request.user.get_short_name(), returns just the first name

You can also access the attributes directly, with request.user.first_name and request.user.last_name, but it is preferred to use the methods as the attributes may change in future versions.

The django user model has a rich set of methods, which you can read about in the reference for the auth application.

like image 67
Burhan Khalid Avatar answered Nov 12 '22 05:11

Burhan Khalid


You want the first_name and last_name attributes: request.user.first_name and request.user.last_name

like image 4
rofls Avatar answered Nov 12 '22 03:11

rofls