0

I am working on django website and I am using django Auth for user authentication and for authorization of user i am using request.user.is_authenticated() code in django view but using this i have to write this code in each and every view, because in my site there is only homepage, registration page and login page which can be accessed without login. So in each and every view i have to right this code.

def dashboard(request):
if request.user.is_authenticated():
    return render(request, 'home/dashboard.py')
else:
    return HttpResponse('User is not logged In')

That's why I want to ask is there any way to write code only once for all views those can not be accessed without login as we do in CakePHP using authcomponent.

Sayse
  • 42,633
  • 14
  • 77
  • 146

2 Answers2

1

Yes, just use the login_required decorator or LoginRequiredMixin

from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
    return render(request, 'home/dashboard.py')

from django.contrib.auth.mixins import LoginRequiredMixin
class MyCBV(LoginRequiredMixin, GenericView):

What this will do is redirect anyone attempting to access the view back to the LOGIN_URL (which can be overridden here) with a next get parameter back to the view, so that they must login before continuing. This isn't the same as what you currently do, but its much friendlier

If your entire website needs to be logged in, then you can use a middleware to make this the default

Community
  • 1
  • 1
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • added @login_required but it is showing name 'login_required' is not defined error –  Aug 25 '16 at 07:40
  • @PankajSharma - You need to import it – Sayse Aug 25 '16 at 07:41
  • Thanks, now it is not giving any error but when i tried to access dashboard view without login it's redirecting me to it's default login page, how can i customize this functionality, because both my login and registration from are on registration_login view. –  Aug 25 '16 at 07:46
  • Or you could set the `LOGIN_URL` correctly, in your settings. – Sayse Aug 25 '16 at 07:58
0

You can use @login_required instead. See here

User_Targaryen
  • 4,125
  • 4
  • 30
  • 51