Question

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.

Was it helpful?

Solution

@login_required should 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_required decorator:

@login_required
def do_something(request):
  pass

def do_something_else(request):
  pass

def index(request):
  if request.user.is_authenticated:
    do_something(request)
  else
    do_something_else(request)

But in this case this decorator is unnecessary because do_something will run only if the user is authenticated. However, too much security is not evil.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top