Search code examples
pythondjangotemplatesdjango-allauth

Using Django Templates with User Authentication


I have a site which I am using user authentication to limit access to. I am using django-allauth to handle social media authentication, but want to limit access to staff accounts only (set in the django admin panel).

I want to use a template as a header (bootstrap, nav bar etc.) with the main content loaded afterwards, or a message asking the user to login or request to be verified by admins.

My header template file: inventory/header.html

<body>
    {% load bootstrap3 %}

    {% if user.is_authenticated %}
        {% if user.is_staff%}
            {% block main %}{% endblock %}
            {% block scripts %}{% endblock %}
        {% else %}
            <h1>Please ask an administrator to activate your account</h1>
        {% endif %}
    {% else %}
        <h1>Please login to see this page</h1>
    {% endif %}
</body>

And another template called by the view: inventory/home.html

{% include "inventory/header.html" %}
{% block main %}
    This is the home page.
{% endblock %}

The view:

def home(request):
    return render(request,'inventory/home.html')

Whenever I call the view, regardless of whether the user is logged in or a staff member, the main block is always displayed. The other error messages are displayed correctly.

I'm trying to avoid inserting is_authenticated/is_staff into all of my templates. I have also thought about using the login_required view decorator but that does not solve my is_staff issue.


Solution

  • Turns out I should have used

    {% extends "inventory/header.html" %}
    

    instead of

    {% include "inventory/header.html" %}
    

    Doh!