Is Django better to check user.is_authenticated in views.py or in a template?

I have a homepage on which I want to display the login form when the user is not logged in or displays a list of items that belong to this user if he is already logged in.

So far I have come up with 2 methods:

  • Check if the user is authenticated in views.py and displays the corresponding view (in my views.py):

    if request.user.is_authenticated():
        return render(request, 'items.html')
    else
        return render(request, 'login.html')
    
  • Check directly in the template and create the appropriate HTML for each case (in my index.html):

    {% if user.is_authenticated %}
        HTML for my items list
    {% else %}
        HTML for my login form
    {% endif %}
    

Question

So, which method handles this better? Are these methods very different in performance? Is there any standard we need to handle in views.py or in the template itself?

+4
3

, . , MVC.

A template , view. , , , , . , .

+2

html. , :

{% if user.is_authenticated %}
    <h3>Welcome</h3>
{% else %}
    <a href="/path/to/login">Login</a>
{% endif %}

items.html login.html - , .

+1

TL; DR

Python, . - .

Elaborate

  • : -, , . ;
  • > : , , ( ).
  • : , , , ?
  • : , , . (, , );
  • : , ;
  • : (HTML/CSS ), , -.
0

Source: https://habr.com/ru/post/1607593/


All Articles