首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Django:我如何将login_required装饰器应用于我的整个站点(静态媒体除外)?

Django:我如何将login_required装饰器应用于我的整个站点(静态媒体除外)?
EN

Stack Overflow用户
提问于 2010-07-10 00:23:22
回答 6查看 21.7K关注 0票数 25

example为应用程序级别的视图提供了一个片段,但是如果我的"urls.py“文件中有许多不同的(和一些非应用程序的)条目,包括模板,该怎么办?我如何将这个login_required装饰器应用到它们中的每一个呢?

(r'^foo/(?P<slug>[-\w]+)/$', 'bugs.views.bug_detail'),
(r'^$', 'django.views.generic.simple.direct_to_template', {'template':'homepage.html'}),
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-07-13 22:54:29

把它放到我的项目根目录下的middleware.py文件中(取自http://onecreativeblog.com/post/59051248/django-login-required-middleware)

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)

然后在settings.py中将projectname.middleware.LoginRequiredMiddleware附加到我的MIDDLEWARE_CLASSES。

票数 28
EN

Stack Overflow用户

发布于 2013-02-17 16:58:56

对于那些后来了解这一点的人,你可能会发现django-stronghold非常适合你的用例。您将所有想要公开的urls列入白名单,其余的都需要登录。

https://github.com/mgrouchy/django-stronghold

票数 13
EN

Stack Overflow用户

发布于 2013-05-13 21:27:35

这里有一个稍微短一些的中间件。

from django.contrib.auth.decorators import login_required

class LoginRequiredMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        if not getattr(view_func, 'login_required', True):
            return None
        return login_required(view_func)(request, *view_args, **view_kwargs)

在不需要登录即可查看的每个视图上,您必须将"login_required“设置为False:

函数-视图:

def someview(request, *args, **kwargs):
    # body of view
someview.login_required = False

基于类的视图:

class SomeView(View):
    login_required = False
    # body of view

#or

class SomeView(View):
    # body of view
someview = SomeView.as_view()
someview.login_required = False

这意味着您必须对登录视图做一些处理,但无论如何,我总是要编写自己的auth-backend。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3214589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档