繁体   English   中英

Django 员工登录所有网址

[英]Django staff login to all urls

我想定义一些以 /staff/* 开头的特定 url 以仅供员工访问。 所以只有员工可以访问以 /staff/* 开头的 url

我如何在 Django 中定义它?

您可以将user_passes_teststaff_member_required装饰器用于与您的网址相关联的视图(以/staff/开头),示例如下:

使用user_passes_test装饰器:

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_staff, login_url='/some_url/')
def your_view(request, ...):
    # Only for staff

使用staff_member_required装饰器:

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def your_view(request, ...):
    # Only for staff

使用自定义中间件。 如果url以/ staff /开头,并且request.user不是staff,请引发Http404或向客户端返回一些特殊消息。

下面是一个示例:

对于Django版本<1.10:

class StaffCheckMiddleware(object):
    def process_request(self, request):
        full_path = request.get_full_path()
        if full_path.startswith('/staff/') and not request.user.is_staff:
            raise Http404      

对于Django 1.10或更高版本:

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

    def __call__(self, request):
        full_path = request.get_full_path()
        if full_path.startswith('/staff/') and not request.user.is_staff:
            raise Http404

        response = self.get_response(request)
        return response

然后在settings.py添加StaffCheckMiddleware

对于基于类的视图,我只是使用了 django 源代码中的 LoginRequiredMixin,并使用这个基础创建了一个新的 mixin:

website/utils/is_staff_mixin.py

from django.contrib.auth.mixins import AccessMixin
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.shortcuts import redirect


class IsStaffMixin(AccessMixin):
    """Verify that the current user has staff status."""
    def handle_no_permission(self, request):
        messages.add_message(request, messages.ERROR, _("You need higher permissions in order to access this page."))
        return redirect("index")


    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            messages.add_message(request, messages.ERROR, _("You need to be logged in in order to access this page."))
            return redirect("login")
        if not request.user.is_staff:
            return self.handle_no_permission(request)
        return super().dispatch(request, *args, **kwargs)

如果用户未登录,我将重定向到登录页面。 如果用户已登录但没有将is_staff var 设置为True ,我将重定向到我的主页。

这是一个真实世界的例子:

website/apps/gallery/views.py

from website.utils.is_staff_mixin import IsStaffMixin
from django.views.generic import DetailView, ListView

from .models import Gallery


class ListGalleriesView(IsStaffMixin, ListView):
    model = Gallery
    paginate_by = 5
    context_object_name = "galleries"
    queryset = Gallery.objects.all().order_by("-date_added")


class GalleryView(IsStaffMixin, DetailView):
    model = Gallery
    context_object_name = "gallery"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM