python - Template not rendering properly with if user.is_authenticated for Django -
i'm trying incorporate template tag/inclusion tag sidebar site. main section of page updates when put:
{% if user.is_authenticated %} <h1> hello {{ user.username }} {% else %} <h1> hello </h1> {% endif %}
when try use same principle in template tag/sidebar, seems ignore user.is_authenticated , show 'login' , 'register', when should showing 'logout'.
the body of html (main index page):
{% load kappa_extras %} <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-2" id="side_section"> {% block sidebar %} {% get_game_list %} {% endblock %} </div> <!--main section--> <div class="col-sm-10" id="main_section"> {% block body %} {% endblock %} </div> </div> </div>
the get_game_list function 'kappa_extras':
from django import template kappa.models import game, game_page django.contrib.auth.models import user register = template.library() @register.inclusion_tag('kappa/sidebar.html') def get_game_list(): return {'game_list': game.objects.all()}
and 'kappa/sidebar.html':
<div id="side_default_list"> <ul class="nav"> <li><a href="{% url 'index' %}">kappa</a></li> {% if user.is_authenticated %} <li><a href="{% url 'user_logout' %}">log out</a></li> {% else %} <li><a href="{% url 'user_login' %}">log in</a></li> <li><a href="{% url 'register' %}">register</a></li> {% endif %} </div>
i checked few older inquires though none of them working properly. tried putting request def get_game_list(request): said did not receive value argument. how sidebar update when user.is_authenticated?
you need pass user inclusion tag.
@register.inclusion_tag('kappa/sidebar.html') def get_game_list(user): return {'game_list': game.objects.all(), 'user': user}
then in template, call tag
{% get_game_list user %}
alternatively, can set takes_context=true
in inclusion tag, can access user template context.
@register.inclusion_tag('kappa/sidebar.html', takes_context=true) def get_game_list(context): return {'game_list': game.objects.all(), 'user': context['user']}
in case, don't need pass user template tag more.
{% get_game_list %}
see the docs more information , other examples.
Comments
Post a Comment