I am using the django User model
to store user's information. Now after login I want to redirect the user to the dashboard where a message should be delayed: Welcome <his_first_name>. I tried the following code:
@login_required(login_url='login')
def dashboard(request):
return render(request, 'accounts/dashboard.html', {"name": user.first_name})
but I am getting the following error: name 'user' is not defined
. What am I missing?
my register function looks something like this:
from django.contrib.auth.models import User
def register(request):
if request.method == 'POST':
firstname = request.POST['firstname']
lastname = request.POST['lastname']
username = request.POST['username']
password = request.POST['password']
user = User.objects.create_user(first_name=firstname, last_name=lastname, username=username, password=password)
user.save()
return redirect('login')
In the above code, what I understand is that user
is an object of the User
class, then how can all objects have the same name user, what am I misunderstanding?
Edit: thanks to the answers below, I missed the request keyword before user.first_name, it should have been:
return render(request, 'accounts/dashboard.html', {"name": request.user.first_name})
Get user from request
request.user
and use in your function.
@login_required(login_url='login')
def dashboard(request):
return render(request, 'accounts/dashboard.html', {"name": request.user.first_name})
Safe way to get user's first name:
request.user.get_short_name()
Also you can get full name using:
request.user.get_full_name()