Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django,将所有未经身份验证的用户重定向到登录页_Python_Django - Fatal编程技术网

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

Python Django,将所有未经身份验证的用户重定向到登录页,python,django,Python,Django,我有一个django网站,有很多URL和视图。现在我要求将所有未经身份验证的用户重定向到某个登录页。因此,所有视图都必须检查user.is\u authenticated(),并返回到一组新的登录页 它能以一种很好的方式完成,而不是像我的views.py/url.py那样乱来吗?查看文档了解更多信息 另一个选项是将其添加到URL.py模式中,请参见 您可以使用中间件 类似的内容将检查每个请求的用户身份验证: class AuthRequiredMiddleware(object): de

我有一个django网站,有很多URL和视图。现在我要求将所有未经身份验证的用户重定向到某个登录页。因此,所有视图都必须检查user.is\u authenticated(),并返回到一组新的登录页

它能以一种很好的方式完成,而不是像我的
views.py
/
url.py
那样乱来吗?

查看文档了解更多信息

另一个选项是将其添加到URL.py模式中,请参见


您可以使用中间件

类似的内容将检查每个请求的用户身份验证:

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

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

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

这可以通过中间件实现

我发现了一个非常漂亮的Django代码片段,它完全符合您的要求。您可以找到它,它看起来像:

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)
您只需将文件保存为
middleware.py
,并将该类包含在settings.py中,即

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

您还可以在
settings.py
中定义一个
LOGIN\u URL
,以便重定向到自定义登录页面。默认的
LOGIN\u URL
'/accounts/LOGIN/'

从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: # in Django > 3 this is a boolean
            return HttpResponseRedirect('login')
        
        # Code to be executed for each request/response after
        # the view is called.

        return response

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


也许太晚了,但在django 1.9+中太容易了。 Django引入了泛型类,这是一个很好的例子 借

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

from django.contrib.auth.mixins import LoginRequiredMixin

class BlogUpdateView(LoginRequiredMixin, UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body']
您还可以用于方法请求

from django.contrib.auth.decorators import login_required

@login_required(login_url='/login/')

def home(request):
    return render(request, "home.html")

它是这样显示的:

通过设置
login\u url
可以避免指定
login\u url

因此,在
settings.py
中添加:

LOGIN\u URL=''
并且在您的
视图.py中
仅使用
@login\u required
注释相关函数:

@需要登录\u
定义某些视图功能(请求):
如果需要在视图函数中重定向,可以使用以下方法:

return redirect\u to\u login(request.get\u full\u path())

django bundle()使您的所有视图都按默认值登录\u这是我希望避免的。向我的所有视图添加装饰器并更改我的所有url操作。另一方面,我不想重定向到登录,而是要重定向到另一个页面。如果用户愿意,可以从该页面登录离开。虽然这并没有解决OP问题,但它仍然提供了一个很好的解决方案。我想补充的是,你的装饰可以有一个重定向;示例@login\u required(login\u url='/accounts/sign')我认为您需要移动您的
self.get\u response(request)
调用,以便它位于
请求之后。user.is\u authenticated()
检查。按照编写方式,未经身份验证的请求将运行视图代码,该代码将生成响应,然后身份验证检查将用重定向到登录页面的方式替换该响应。无论如何,视图代码中的任何更新/删除都应该受到权限检查的限制,但最好不要冒险。优雅的解决方案非常完美,工作起来很有魅力。已将登录和注销URL添加到我的登录/注销URL中,它们可以帮助实现完美的重定向。谢谢分享。这对一个班级来说不起作用吗?我创建了一个继承自Django LoginView的类
CustomLoginView(LoginView)
但是我有一条错误消息:
path('login/',views.CustomLoginView.as_view(),name='login')
@Solal Use
LoginRequiredMixin
例如
类someView(LoginRequiredMixin,CreateView):
等。在正文中,不要忘记添加
登录url
以将页面重定向到。这个答案有些过时。对于Django的当前版本,最好在下面查看@AriG的答案。但该解决方案需要为每个视图指定登录url。OP说他希望所有视图的所有未经验证的请求都发生这种情况。对于像我这样被最近的更改绊倒的人,
已通过身份验证()
不再是可调用的,现在它只是一个布尔变量,所以删除
()
:)
from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):
    ...
from django.contrib.auth.mixins import LoginRequiredMixin

class BlogUpdateView(LoginRequiredMixin, UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body']
from django.contrib.auth.decorators import login_required

@login_required(login_url='/login/')

def home(request):
    return render(request, "home.html")