1

I need to get the username to show it in

<li>
    <a tabindex="-1" href="base_pages_profile.html">
       <i class="si si-user pull-right"></i>
            <span class="badge badge-success pull-right"></span>USERNAME
    </a>
</li>

I have tried using request.user.username and request.get_username and this does not work, is there any other way to this?

4 Answers 4

4

Ensure your request user is an authenticated user. An anonymous user is used if the user is not authenticated, in which case, username is not present.

If you can include your view and the full template in your example it would help to better answer your question.

Tip: Inspect request.user.pk to see if the user actually exists. request.user.is_anonymous and request.user.is_authenticated are also available.

Reference:

https://docs.djangoproject.com/en/1.9/ref/contrib/auth/

2

Anything you want to access inside the template you need to pass in the context. So in your view you would have something like

def someview(request):
    template = loader.get_template('someview.html')
    context = {
        'username': request.user.username,
    }
    return HttpResponse(template.render(context, request))

and in your template you can have

<span class="badge badge-success pull-right"></span>{{ username }}

Alternatively you can use context processors to expose request or user or both to the templates by default https://docs.djangoproject.com/en/dev/ref/templates/api/#context-processors

2

If you are using Django's built-in user management, make sure it is properly installed.

Particularly, in your settings, you should have at least:

  • 'django.contrib.auth' in INSTALLED_APPS
  • 'django.contrib.auth.middleware.AuthenticationMiddleware' in MIDDLEWARE_CLASSES
  • 'django.contrib.auth.context_processors.auth' in your template engine's context processors

If you have created your django project with django-admin startproject, all of these should already be in place

1

Just wondering maybe this is what you need if your view function argument include 'request', eg, you want to show the user who login:

 <span class="badge badge-success pull-right"></span>{{ request.user }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.