Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 %}
<h1>
    Welcome to the show
</h1>
If do something like it, works:

```html
{% if not request.user.is_staff %}
<h1>
    Welcome to the show
</h1>

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 views.py.

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading