Django: send SESSION value to an extendable html template

Viewed 233

One the one hand i have an navbar.html template that can be extended by several other html templates. On the other hand in my views i have a login system and when a user logs in im creating a session value with user's name. i want to send this session value to the navbar html but without rendering this template. How could i do this?

login in view.py

name = form.cleaned_data.get('name')
password = form.cleaned_data.get('password')
user = Users.objects.filter(name=name, password=password)

if user.count() > 0:
    request.session['user'] = user.name

    return redirect("store/")

else:
    messages.info(request, 'Invalid credentials')
    return redirect("/login/")

the return redirect("store/")redirects to the store.html that extends the navbar.html. I want to send request.session['user'] to the navbar.html

1 Answers

When you render multiple templates extended into each other, Django treats them as a single merged page. Anything that is available in one is available in the other as well. If you pass the session info to your template it's also automatically available in your navbar. All you gotta do is adding some conditional logic to prevent the navbar throwing an error when you open it without the session information.

In your view you have to include the session information in the context.

#view
context['session'] = request.session

and render the template with that context

#view
return render(request, "template.html", context)

Then in your template you can access {{ session }} freely. To display it in your navbar and not having errors pop up just add an if statement:

#navbar.html    
{% if session %} Welcome back {{ session.user }} {% endif %}

Consider that if all the information that you want to display is about the currently logged in user you probably don't need to do any of this. Just use any class-based view (I'm not sure about function-based views as i rarely use them) and in your templates you can always reference {{ user }} and all its attributes without having to manually pass it to the template through a context variable.

In a way the logged in user in DTL is global.

In that case you can simply go with

#navbar.html
{% if user.is_authenticated %}
    <p>Hello, {{ user.first_name }} {{ user.last_name }}!</p>
{% else %}
    <p>Hello, guest!</p>
{% endif %}
Related