Reputation: 2698
On my html, I can check if the user is logged in by using the following syntax:
{% if user.is_authenticated %}
<div id="display_something">...</div>
{% else %}
<p>Please Log in</p>
{% endif %}
But what should I do if I want to check if the user is authenticated for every html file I am rendering? Do I have to copy and paste that {% if ... %}
block for every single html file? What is the Django's way of handling this issue? What's the good practice?
Upvotes: 4
Views: 8495
Reputation: 3611
You shouldn't handle the authentication logic in the template (for the entire site), instead you can use the login_required decorator on your views.
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
Upvotes: 5
Reputation: 731
in your base.html
, add your check
{% if user.is_authenticated %}
{% block page %}
{% endblock %}
{% else %}
<p>Please Log in</p>
{% endif %}
then with all your other pages, add {% extends 'base.html' %}
at the top. You will need to give it a relative link to base.html
.
Then the rest of your code on that page needs to sit between tags like below.
{% block page %}
<!-- all your html code here -->
{% endblock %}
Notice that after block
, you need to have the same name. for this example, it is page
but you can pick your own variable name.
Upvotes: 7