I have a homepage, which I want to display a login form when user is not logged in or display a list of items belong to that user if he/she already logged in.
So far I came up with 2 methods:
Check whether user is authenticated in views.py and render 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 template and generate corresponding HTML for each case (in my index.html ):
{% if user.is_authenticated %} HTML for my items list {% else %} HTML for my login form {% endif %}
So which method is better for handling this? Are those methods differ much in performance? Is there any standard that we should handling these in views.py or in template itself?
I don't think there is a big performance difference. What's most important is how much you should stick to MVC
pattern.
A template
is meant to just display some sort of data that the view
provides. Any kind of logic like deciding what kind of data to show based on requester's state should always be implemented by the view. Thus, you should move your logic into view function for the cleanness of your design.
Logic should be in your python code, not your template as much as possible. Due to maintenance and future-proof reasons .
It depends on your html. If you want to change only a little part of your code based on the condition, check inside a template:
{% if user.is_authenticated %}
<h3>Welcome</h3>
{% else %}
<a href="/path/to/login">Login</a>
{% endif %}
But if items.html
and login.html
are different and big templates, you should definitely do the login inside your view.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.