Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - check if user is authenticated for every url

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?

like image 457
Eric Kim Avatar asked Jan 01 '23 21:01

Eric Kim


2 Answers

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.

like image 131
Bill F Avatar answered Jan 13 '23 00:01

Bill F


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):
    ...
like image 22
Johan Avatar answered Jan 13 '23 00:01

Johan