首页 > 解决方案 > 使当前用户只能访问用户配置文件

问题描述

所以我想做一个页面,让用户可以看到他们的一些细节。没有其他人可以看到此页面。

网址是

path('accounts/perfil/<int:pk>', views.Perfil.as_view()),

所以我需要检查登录的用户是否与url中的相同。如何使用基于类的视图来做到这一点?

标签: django

解决方案


您不需要在 url 中传递 id。您可以从 request.user 访问已登录的用户,并且可以使用 is_authenticated() 进行检查。

path('accounts/profile/', views.Profile.as_view()),

class Profile(TemplateView):
  def get(self, request, *args, **Kwargs):
      if request.user.is_authenticated():
        ## send details
      else:
        return other

用于休息 api

class Profile(APIView):
   permission_classes = (permission.IsAuthenticated,)
   def get(self, request,*args, **kwargs):
      return response.Response(UserSerailizer(request.user).data)

如果你想在 url 中添加 id

class Profile(Temaplet):
  def get(self, request, *args, **kwargs):
     user = User.objects.get(id=kwars['id'])
     if user.is_authenticated():
        ## do action

推荐阅读