我继承了一个Django(1.5.1)项目,我需要在@login_required
装饰器后面放一个视图。以下是views.py
中的内容:
我从here获得了这段代码,其目的似乎是允许某人将@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)
没有做好自己的工作。有什么想法吗?
答案 0 :(得分:1)
您可以在urls.py中添加装饰器
from django.contrib.auth.decorators import login_required
url(r'^workers/$', login_required(views.RootWorkerView.as_view()))
这对我有用。
答案 1 :(得分:1)
现在你可以使用 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
答案 2 :(得分:-1)
我在关注者页面上努力解决了这个问题。我终于解决了
我的解决方案:
views.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)
urls.py
from 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"),
]