I’m very new to Django. In my website I was trying to do something like this
#views.py
def index(request):
....
if request.user.is_authenticated:
#do something
else
#something else
So my idea was to have some information from database, displayed if user is logged in.
And I was wondering, is there any way to do it like that:
#views.py
def index(request):
....
@login_required
#do something
....
#do something else for everybody
Or if you think it is a bad practice to do it like that, please give me some ideas how to do it another way. May be I have to change urls.py somehow.
thank you.
@login_requiredshould be used on entire function (a controller, to be more specific). Your first code block is the correct way to do what you want (with the exception of wrong indentation).You can create separate function with
@login_requireddecorator:But in this case this decorator is unnecessary because
do_somethingwill run only if the user is authenticated. However, too much security is not evil.