from django.contrib.auth.decorators import login_required
@login_required(login_url='/example url you want redirect/')
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
# handle view
-------------------------------------------------------------------
# add in settings.py
LOGIN_URL = your_login-page_url
### now if the user attemped to request the view without login ###
### user will be redirected to the login-page using the provided url in settings.py ###
You can add the decorator in the urls.py
from django.contrib.auth.decorators import login_required
url(r'^workers/$', login_required(views.RootWorkerView.as_view()))
now you can use Django builtin LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
def login_view(request):
if request.method == 'GET':
cache.set('next', request.GET.get('next', None))
if request.method == 'POST':
# do your checks here
login(request, user)
next_url = cache.get('next')
if next_url:
cache.delete('next')
return HttpResponseRedirect(next_url)
return render(request, 'account/login.html')
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def my_view(request):
...