Django:如何将login_required装饰器应用于整个网站(不包括静态媒体)? [英] Django: How can I apply the login_required decorator to my entire site (excluding static media)?
本文介绍了Django:如何将login_required装饰器应用于整个网站(不包括静态媒体)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例提供了一个代码段对于应用程序级别视图,但是如果我的urls.py文件中包含许多不同的(和一些非应用程序)条目,包括模板呢?如何将这个login_required装饰器应用于每个装饰器?
The example provides a snippet for an application level view, but what if I have lots of different (and some non-application) entries in my "urls.py" file, including templates? How can I apply this login_required decorator to each of them?
(r'^foo/(?P<slug>[-\w]+)/$', 'bugs.views.bug_detail'),
(r'^$', 'django.views.generic.simple.direct_to_template', {'template':'homepage.html'}),
推荐答案
将其删除为code> middleware.py 文件在我的项目根目录中:
Dropped this into a middleware.py
file in my project root:
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)
然后在设置中追加 projectname.middleware.LoginRequiredMiddleware
到我的MIDDLEWARE_CLASSES .py。
Then appended projectname.middleware.LoginRequiredMiddleware
to my MIDDLEWARE_CLASSES in settings.py.
这篇关于Django:如何将login_required装饰器应用于整个网站(不包括静态媒体)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文