[Answered ]-Django Render function: template not printing variable

1👍

You do not need to pass a username object as context to your view. By default, Django includes that for its template context processors. The User object is stored in a variable called “user”. You can use the User object’s get_username() method. Sample code below:

LoginView.py

def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            print(user)
            print(user.username)
            return render(request, '/')
            # return HttpResponseRedirect('/')
    else:
        return 'Please enter your UN and PW'

profile.html

{% block content %}
<html>
    <head>
        <title>PROFILE</title>
    </head>
<body>
    PROFILE
</body>
<p>
    {{ user.get_username }}
</p>
</html>
{% endblock %}

Make sure you have something like this in your settings.py. Particularly, include django.contrib.auth.context_processors.auth in your template context processors.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

1👍

If the user is authenticated you can access username as

{{ request.user.username }}

But settings must contain

TEMPLATE_CONTEXT_PROCESSORS = (
  # ...
  'django.core.context_processors.request', #'django.template.context_processors.request', in django1.8
  # ...
)

0👍

When you passed username and user, you passed a dict.

{'username': username, 'user':user}

To access these in HTML, just use {{username}} or {{user}}

Leave a comment