How to call a verification function from views to templates?

I have a function to check if the user is a staff:

class VerificateUser():
    def allowed_user(request):
        if request.user.is_staff:
            return True

In my template, I’m going to show this section only for staff users, but this is not working.

{% url if not allowed_user %}
    Welcome to the show
If do something like it, works:

{% if not request.user.is_staff %}
    Welcome to the show

But I need to use a view function to clean my code because I’m probably going to add more conditionals.

>Solution :

Since you are using a class-based view then I would suggest updating the context dictionary which you could use in the html template to determine whether or not the user is allowed or not. For example., Within the

class VerificateUser():
    # Update the context
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Call the allowed_user() and return whatever value, passing that value it to the context variable
        context['allowed_user'] = self.allowed_user()

    return context

    # Checking if the user is allowed here
    def allowed_user():
        if self.request.user.is_staff:
            return True

        return False

Now within the html file, you can reference that allowed_user from the context variable.

{% if allowed_user %}
    <h1>Hi, you are allowed to see here...</h1>
{% endif %}

That should do the trick.

Leave a Reply