1👍
✅
Here is one way: request.user
has a helper method called is_authenticated
, which you can use like this:
ctx = {
'user' : request.user
}
if request.user.is_authenticated():
ctx.update({
'first_name': request.user.first_name,
'last_name': request.user.last_name,
'email' : request.user.email
})
Now, the extra attributes are present only if the user is authenticated
This is, assuming you are using the auth
model of django. If not, please change the model field names accordingly.
On a side note, you should not be passing the entire request object in the context. You should be extracting only the relevant info and sending it in the context.
Now, you can access all these values from the template anyways. Example:
{% if request.user.is_authenticated %}
{{request.user.username}}
{{request.user.email}}
{# etc.. #}
{% endif %}
No need to send anything in the context explicitly. The request
object already has everything
Source:stackexchange.com