我试图以这种方式应用于我的项目:
http://onecreativeblog.com/post/59051248/django-login-required-middleware
这里是我的settings.py
...
LOGIN_URL = '/admin/login/'
LOGIN_EXEMPT_URLS = (
)
MIDDLEWARE = [
...
'project.middleware.LoginRequiredMiddleware',
]
...
这里是我的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:
"""
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally be specified
in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
you can copy from your urls.py).
Requires authentication middleware and template context processors to be
loaded. You'll get an error if they aren't.
"""
def process_request(self, request):
assert hasattr(request, 'user'), "The Login Required middleware\
requires authentication middleware to be installed. Edit your\
MIDDLEWARE_CLASSES setting to insert\
'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
'django.core.context_processors.auth'."
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)
我将中间件.py放在我的项目根目录上。
project
|__db.sqlite3
|__manage.py
|__middleware.py
|__app
|___admin.py
|___views.py
|___models.py
但收到了错误。
django.core.exceptions.ImproperlyConfigured: WSGI application
'project.wsgi.application' could not be loaded; Error importing
module: 'No module named 'project.middleware'
答案 0 :(得分:2)
project
目录(包含manage.py
的目录)位于python路径上。因此,您不应该在该目录中包含模块的project.
前缀。
将您的MIDDLEWARE
设置更改为:
MIDDLEWARE = [
...
'middleware.LoginRequiredMiddleware',
]
答案 1 :(得分:0)
最好使用login_required
装饰器而不是中间件。因为将为每个请求执行中间件。因此,只需使用login_required
装饰器装饰视图。
from django.contrib.auth.decorators import login_required
@login_required
def user_detail(request):
# some code