B
B
BogBel2015-11-15 02:38:21
Django
BogBel, 2015-11-15 02:38:21

How to use custom filter in template (Django,Python)?

Groups are stored in the database (only two)
1) admins
2) users
It is necessary from the template, depending on whether the authenticated user is a member of the admin group or not, show or hide the access button to the panel.

register = template.Library()


@register.filter(name='has_group')
def has_group(user, group_name):
    group = Group.objects.get(name=group_name)
    return True if group in user.groups.all() else False

and shtml
{% block content %}
<header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="./" class="navbar-brand">Web App</a>
    </div>
    <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation">
      <ul class="nav navbar-nav">
        <li>
          <a href="#">Getting started</a>
        </li>

        <li>
          <a href="#">Components</a>
        </li>
        {% if{{ request.user|has_group:"admins"}} %}
        <li>
          <a href="/admin_panel/">Admin Panel</a>
        </li>
        {% endif %}
          {% if request.user.is_authenticated%}
        <li class="active">
          <a href="/login">Logout</a>
        </li>
          {% else %}
          <li class="active">
          <a href="/logout">Login</a>
        </li>
          {% endif %}
      </ul>
    </nav>
  </div>
</header>
{% endblock %}

Namely, the problem is connected with this section
{% if{{ request.user|has_group:"admins"}} %}
        <li>
          <a href="/admin_panel/">Admin Panel</a>
        </li>
        {% endif %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-11-15
@sim3x

stackoverflow.com/questions/20469174/whats-the-dif...
"group of admins" sounds weird there is a staff and there is a superuser
Why multiply entities?

{% if request.user.is_staff %}
<li>
   <a href="{% url "staff"%}">Admin Panel</a>
</li>
{% endif%}

{% if request.user.is_superuser %}
<li>
   <a href="{% url "admin"%}">Admin Panel</a>
</li>
{% endif%}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question