Search code examples
djangodjango-templatesdjango-users

Django: trying to pass users first name to template but getting a weird code instead


In views.py I have:

def loggedin(request):
   return render_to_response('theDB/loggedin.html', {'first_name': User.first_name })

In loggedin.html I have:

<h2>Hi {{ first_name }} you are now logged in!</h2>
<p>Click <a href="/accounts/logout/">here</a> to logout.</p>"

This is what I get in the browser:

Hi "<"django.db.models.query_utils.DeferredAttribute object at 0x0000019FD7AA7AC8> you are now logged in!
Click here to logout.

Instead of seeing the user's first name, I see that weird thing (a unicode object?)


Solution

  • User is the model class, not the current logged in user. You can use request.user in your view.

    def loggedin(request):
        return render(request, 'theDB/loggedin.html', {'first_name': request.user.first_name)
    

    Note I have used the render shortcut, which is recommended instead of render_to_response.