Some of my views have decorators that restrict access, like so:
@user_passes_test(my_validation_function)
def my_restricted_view(request):
...
The thing is, in my templates I would like to hide the links for which the user does not have access, according to the logic in my_validation_function
.
I understand that one way of doing this would be defining a custom filter that basically calls my_validation_function
(say my_validation_filter
), and shows/hides the link accordingly. Something like this:
{% if request | my_validation_filter %}
<a href="{% url 'my_restricted_view' %}"></a>
{% endif %}
The problem I see here is that I'm linking the validation twice: once in the view, and once in the template. Suppose I have many views, each with different validation logic behind them:
@user_passes_test(my_validation_function)
def my_restricted_view(request):
...
@user_passes_test(my_other_validation_function)
def my_other_restricted_view(request):
...
This would means that, when I'm writing the templates, I have to be careful to always remember which validation function goes with which view.
Is there a way to define a function or that reverses the URL, and then checks the validations defined in the decorator of the view? I'm thinking something like these:
{% if can_access 'my_restricted_view' %}
{# this implicitly calls 'my_validation_function' #}
...
{% endif %}
{% if can_access 'my_other_restricted_view' %}
{# this implicitly calls 'my_other_validation_function' #}
...
{% endif %}
Basically what I want is to only have to change the validation logic for each view in one place, and not touch my templates as much.