限制django中的用户

Restrict users in django

我有一个面板来管理管理员或管理员用户的帖子。 我如何限制面板并只显示给管理员而不显示在系统中注册的其他用户。

查看:

class IndexView(LoginRequiredMixin, ListView):
    model = Post
    template_name = 'panel/index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context["posts"] = Post.objects.all()
        context["counter"] = self.post_counter(context["posts"])
        return context

    def post_counter(self, posts):
        postNumber = 0
        for post in posts:
            postNumber +=1

        return postNumber

您可以创建视图的 mixin,它要求用户是管理员:

class AdminRequiredMixin:
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_staff:
            return redirect(WHERE_YOU_WANT)
        return super().dispatch(request, *args, **kwargs)

因为你有 CBV,你可以使用 PermissionMixin 然后指定权限。像这样:

from django.contrib.auth.mixins import PermissionRequiredMixin

class MyView(PermissionRequiredMixin, View):
   permission_required = ("is_staff", "is_superuser", )
   ....

参考:https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.mixins.PermissionRequiredMixin

如果您要使用基于函数的视图,则可以使用 @staff_member_required

像这样:

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

@staff_member_required
def my_view(request):
   ...

参考和进一步阅读:https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.views.decorators.staff_member_required

在模板中,您可以通过直接检查用户来做到这一点

{% if user.is_superuser %}
    <p>I'm an admin.</p>
{% else %}
    <p>I'm an user.</p>
{% endif %}