Python Django,将所有未经身份验证的用户重定向到登录页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21123559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:06:46  来源:igfitidea点击:

Django, redirect all non-authenticated users to landing page

pythondjango

提问by xpanta

I have a django website with many urls and views. Now I have asked to redirect all non-authenticated users to a certain landing page. So, all views must check if user.is_authenticated()and return to a new set of landing pages.

我有一个 django 网站,其中包含许多网址和视图。现在我要求将所有未经身份验证的用户重定向到某个登录页面。因此,所有视图都必须检查user.is_authenticated()并返回到一组新的登录页面。

Can it be done in a pretty way, instead of messing with my views.py/urls.pythat much?

能不能以一种漂亮的方式完成,而不是把我的views.py/弄得一团糟urls.py

采纳答案by Dmit3Y

You can use Middleware.

您可以使用中间件

Something like this will check user auth every request:

这样的事情将检查用户身份验证每个请求:

class AuthRequiredMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('landing_page')) # or http response
        return None

Docs:process_request

文档:process_request

Also, don't forget to enable it in settings.py

另外,不要忘记在 settings.py 中启用它

MIDDLEWARE_CLASSES = (
    ...
    'path.to.your.AuthRequiredMiddleware',
)

回答by Guy Gavriely

see the docs for login required decorator

请参阅登录所需的装饰器的文档

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    ...

another option is to add it to your urls.py patterns, see this answer

另一种选择是将其添加到您的 urls.py 模式中,请参阅此答案

urlpatterns = patterns('',
    (r'^foo/$', login_required(direct_to_template), {'template': 'foo_index.html'}),
)

回答by Martin Hallén

This can be done with middleware.

这可以通过中间件来完成。

I've found a really nifty djangosnippet that does exactly what you are asking for. You can find it here, and it looks like:

我发现了一个非常漂亮的 djangosnippet,它完全符合您的要求。你可以在这里找到它,它看起来像:

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)

All you have to do is to save the file as middleware.pyand include the class in you're settings.py, i.e.

您所要做的就是将文件另存为middleware.py并将该类包含在您的 settings.py 中,即

MIDDLEWARE_CLASSES += ('projectname.common.middleware.RequireLoginMiddleware',)

You can also define a LOGIN_URLin settings.py, so that you'll be redirected to your custom login page. The default LOGIN_URLis '/accounts/login/'.

您还可以定义LOGIN_URLin settings.py,以便将您重定向到您的自定义登录页面。默认LOGIN_URL值为'/accounts/login/'.

回答by IVI

As of Django 1.10, the custom middleware classes must implement the new style syntax. You can use the following class to verify that the user is logged in while trying to access any views.

从 Django 1.10 开始,自定义中间件类必须实现新的样式语法。您可以使用以下类来验证用户在尝试访问任何视图时是否已登录。

from django.shortcuts import HttpResponseRedirect


class AuthRequiredMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        if not request.user.is_authenticated():
            return HttpResponseRedirect('login')

        # Code to be executed for each request/response after
        # the view is called.

        return response

回答by AriG

There is a simpler way to do this, just add the "login_url" parameter to @login_required and if the user is not login he will be redirected to the login page. You can find it here

有一种更简单的方法可以做到这一点,只需将“login_url”参数添加到@login_required,如果用户未登录,他将被重定向到登录页面。你可以在这里找到

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):
    ...

回答by Alireza Saremi

Maybe too late but in django 1.9+ it's too easy. Django introduced Login Required mixinfor generic classes and this a great example hereby William S. Vincent

也许为时已晚,但在 django 1.9+ 中太容易了。Django的推出需要登录混入了普通班和一个很好的例子 在这里威廉圣文森

simply in your view add LoginRequiredMixin as parent class

只需在您的视图中添加 LoginRequiredMixin 作为父类

from django.contrib.auth.mixins import LoginRequiredMixin

class BlogUpdateView(LoginRequiredMixin, UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body']

Also you can use login_required decoratorfor method request

您也可以使用login_required 装饰器进行方法请求