Hide CRUD buttons in Django templates for users who are not logged in to the system

Asked

Viewed 166 times

2

I would like to hide my system buttons that allow: add, edit and delete data from my templates for users who are not logged in to the system. He can be seen here: https://sirh-marcellobenigno.herokuapp.com

After some consultations, I saw that it can be done this way:

{% if request.user.is_authenticated %}
    ...
    <button>...</button>
    ...
{% else %}
...
{% endif %}

However, various conditions will be added to the templates... would have some more elegant way to do this?

  • 1

    I had a similar problem in Laravel 5. The solution I had was to create the button in one view, where I passed the parameters to create the button. And there, even there already has the verification whether the user has access or not.. I only have the job to include, to verify not...

  • Interesting... what were the parameters in this case? I think it might be an output yes.

  • 1

    Well, in my case I did it this way: @if(auth()->user()->canAccess($rota))link_to_action($rota, 'adicionar', isset($params) ? $params : []) @endif`

  • 1

    It must be hard to understand. Look at these gist that gets easier

  • Thanks @Wallacemaxters, I’ll try this way.

  • It is easier to just pass the name of the url or route, than to pass and check at the same time.

  • It’s a shame I’ve touched so little with this excellent Python :D framework

Show 2 more comments

1 answer

1

I did, following the hint that was passed. I took advantage of the logic in the templates, from includes, as follows:

 {% include 'partials/actions.html' with pk=basin.pk detail='basins:detail' edit='basins:edit' delete='basins:delete' %}

and no include:

<a href="{% url detail pk %}" class="btn btn-primary btn-sm" role="button">
    <span class="glyphicon glyphicon-eye-open" aria-hidden="true" title="Ver"></span>
</a>

{% if request.user.is_authenticated %}

    <a href="{% url edit pk %}" class="btn btn-primary btn-sm" role="button">
        <span class="glyphicon glyphicon-edit" aria-hidden="true" title="Editar"></span>
    </a>
    <a href="{% url delete pk %}" class="btn btn-primary btn-sm" role="button">
        <span class="glyphicon glyphicon-trash" aria-hidden="true" title="Deletar"></span>
    </a>

{% endif %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.