I want to completely close the site for not authorized .. Tell me what's wrong?

Django == 1.9.6 urls.py

from django.conf.urls import url from django.contrib import admin from . import views from django.contrib.auth.models import User if User.is_authenticated: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home_page), ] else: urlpatterns = [ url(r'^admin/', admin.site.urls), ] 
  • urls.py is executed ONCE when starting the server BEFORE any reception of requests from unauthorized - andreymal
  • And besides, first, is_authenticated is not an attribute, it is a method, and secondly, User is a class; to call a method, you must first create an object of this class. - Sergey Gornostaev

1 answer 1

To "mark" a url or a group of urls as requiring authorization, you can use the decorator:

urls.py

 from django.contrib.auth.decorators import login_required urlpatterns = [ ... url(r"^select2/fields/auto.json$", login_required(AutoResponseView.as_view()), name="django_select2-json"), ... ] 

If you want to close the entire site from unauthorized users, then you should use middleware. For example, as follows:

middleware.py

 from django.http import HttpResponseRedirect from django.conf import settings from re import compile EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: if not request.user.is_authenticated(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return HttpResponseRedirect(settings.LOGIN_URL) 

It must be registered in MIDDLEWARE_CLASSES:

settings.py

 MIDDLEWARE_CLASSES = [ ... appname.middleware.LoginRequiredMiddleware, ... ]