8

@login_required我继承了一个 Django(1.5.1) 项目,我需要在装饰器后面放置一个视图。这是我所拥有的views.py

我从这里得到了这段代码,看起来它的目的是允许某人将@login_required装饰器应用于class

class LoginRequiredMixin(object):
    """
    View mixin which verifies that the user has authenticated.

    NOTE:
        This should be the left-most mixin of a view.
    """

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)


class PermissionRequiredMixin(object):
    login_url = settings.LOGIN_URL
    permission_required = None
    raise_exception = False
    redirect_field_name = '/workers/'

    def dispatch(self, request, *args, **kwargs):
        # Verify class settings
        if self.permission_required == None or len(
            self.permission_required.split(".")) != 2:
            raise Error("'PermissionRequiredMixin' requires "
                "'permission_required' attribute to be set.")

        has_permission = request.user.has_perm(self.permission_required)

        if not has_permission:
            if self.raise_exception:
                return HttpResponseForbidden()
            else:
                path = urlquote(request.get_full_path())
                tup = self.login_url, self.redirect_field_name, path
                return HttpResponseRedirect("%s?%s=%s" % tup)

        return super(PermissionRequiredMixin, self).dispatch(
            request, *args, **kwargs)

然后我将其应用于我想添加权限的视图,如下所示:

class RootWorkerView(LoginRequiredMixin, PermissionRequiredMixin, APIView):
    renderer_classes = (WorkersJSONRenderer, JSONRenderer,
                        BrowsableAPIRenderer)

    def get(self, request):
        worker_list = rest_models.WorkerList(request)
        serializer = WorkerListSerializer(worker_list)
        return Response(serializer.data)

这个APIView论点是一个结转,就像以前它是唯一的论点一样。这个对吗?

跑步时,我什么也得不到。我要保护的视图模板显示时没有登录提示。

相关片段来自urls.py

url(r'^workers/$', views.RootWorkerView.as_view(),
    name='root_worker_view'),

url(r'^login/$', 'django.contrib.auth.views.login',
    {'template_name': 'dashboard/login.html'}),

/login/确实有效,我可以成功登录,所以这不是问题。

我觉得没有@method_decorator(login_required)做它的工作。有任何想法吗?

4

3 回答 3

15

您可以在 urls.py 中添加装饰器

from django.contrib.auth.decorators import login_required
 url(r'^workers/$', login_required(views.RootWorkerView.as_view()))

这对我有用。

于 2016-11-28T05:44:21.350 回答
4

现在你可以使用 Django 内置 LoginRequiredMixin

from django.contrib.auth.mixins import LoginRequiredMixin

class MyView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

https://docs.djangoproject.com/en/3.2/topics/auth/default/#the-loginrequired-mixin

于 2021-07-19T00:05:51.867 回答
-1

我在关注者页面尝试了这个问题。我终于解决了

感谢这个文档

我的解决方案:

视图.py

class AddFollower(LoginRequiredMixin,View):    
    login_url = "/user/login/"

    
    def post(self,request,pk,*args,**kwargs):
        profile = Profile.objects.get(pk=pk)
        profile.following.add(self.request.user)
        return redirect('follower:profile-detail',pk=profile.pk)

网址.py

从 django.urls 导入路径。导入视图

app_name="follower"

urlpatterns = [
   
    path('detail/<pk>/',views.ProfileDetailView.as_view(),name='profile-detail'),
    path('<pk>/add',views.AddFollower.as_view(),name="add-follower"),
    path('<pk>/remove',views.RemoveFollower.as_view(),name="remove-follower"),
    
    ]
于 2021-07-19T01:20:26.560 回答