对所有视图应用django身份验证



我正在尝试为views.py文件中的所有视图实现Django基本身份验证。虽然我可以在每个视图中添加身份验证代码片段,但将其应用于即将发布的视图并不容易。有没有办法让我的views.py中的每个视图都自动检查身份验证?

views.py

def mgmt_home(request):
##############################################################
# This code is repetitive
##############################################################
if request.user.is_anonymous:
return redirect("/login")
##############################################################
test_name = Test.objects.all()[0].test_name
metadata = {
"test_name": test_name,
}
return render(request, "mgmt_home.html", metadata)

有什么方法可以在我的所有视图中避免这个repetitive代码吗?

您可以使用django身份验证中的'login_required(('装饰器或'LoginRequiredMixin'类。https://docs.djangoproject.com/en/3.1/topics/auth/default/

如何在django中指定login_requested重定向url?

您有两个选项:

  1. 来自django.contrib.auth.decorators import login_required

您可以将@login_required((装饰器添加到您的每个视图中,它将在用户未登录时自动将用户重定向到登录页面(或您想将用户发送到的任何页面(。

  1. 在您的情况下,我不建议使用此选项,因为这可能是一种过度使用,对于您的简单问题来说不是必需的。解决方案是创建一个自定义中间件并将代码添加到其中,当然,然后将中间件添加到Settings.py文件中。这样,每次运行您的视图时,您的中间件都会在此之前运行。事实上,这就是中间件的目的。它们的设计目的是减少冗余和像你这样的问题

在python路径上的任何位置创建一个middleware.py文件。将以下代码添加到您创建的中间件.py文件中

from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
def redirect_to_login():
return HttpResponseRedirect(reverse_lazy('users:login'))

class AuthPageProtectionMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
if request.user.is_authenticated:
if not request.user.is_admin:
return redirect_to_login()
else:
return redirect_to_login()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response

您可以将重定向URL替换为特定于应用程序的URL。

最新更新