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?
Check the Logged in User in Views in Django We can use request. user. is_authenticated to check if the user is logged in or not. If the user is logged in, it will return True .
is_authenticated which is always False ). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn't check if the user is active or has a valid session.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With