Reputation: 3262
I'm using standart django template sintaxis for hiding a part of content from template depends on user status. For example
{% if request.user.head_of_dept or request.user.seller or request.user.is_staff %}
I know how to use the dispatch function to restrict user rights, for example
class CustomCrudUserMixin():
def dispatch(self, request, *args, **kwargs):
"""Return 403 if flag is not set in a user profile. """
if not request.user.head_of_dept or request.user.seller or request.user.is_staff:
return HttpResponseForbidden()
return super().dispatch(request, *args, **kwargs)
Sometimes templates contain a lot of places where I have to use restrictions, I'm wondering if there's a way to redo the dispatch function so that don't have to use the syntax {} at the template?
Upvotes: 0
Views: 50
Reputation: 2046
I'd say that the perhaps easy way is to create a simple template tag and use that across all your templates.
from django import template
register = template.Library()
@register.filter(name='user_status')
def user_status(user):
return any([user.head_of_dept, user.seller, user.is_staff])
Then on your templates you import and use this template tag passing the user to it.
{% load user_status %}
{% if request.user|user_status %}
Upvotes: 1