Venkatesh Panabaka
Venkatesh Panabaka

Reputation: 2154

How to change template based on user authentication in django

If user successfully login i need to show one template. if user not login i need to show another template.

I created two templates one is base.html another one is base_login.html template.

IF user successfully login i need to call base_login.html other wise base.html. i am using below to achieve this. it's not giving expected result. How do achieve this?

{% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p> 
        {% extends "base_login.html" %} 
{% else %}
        {% extends "base.html" %} 
{% endif %}

Upvotes: 0

Views: 1846

Answers (1)

binpy
binpy

Reputation: 4194

If your template goes invalid, I suggest you to it at the views.py, an example:

from django.shortcuts import render, render_to_response

def homepage(request):
    template_name = 'homepage.html'
    extended_template = 'base_login.html'

    if request.user.is_authenticated():
        extended_template = 'base.html'

    return render(
        request, template_name, 
        {'extended_template': extended_template, ...}
    )

# homepage.html
{% extends extended_template %}

{% block content %}
  {% if request.user.is_authenticated %}
    Hello {{ request.user }}
  {% endif %}
{% endif %}

Note: if function of render still doesn't work well, please try with render_to_response such as this answer: https://stackoverflow.com/a/1331183/6396981

Upvotes: 1

Related Questions