django - 使当前用户只能访问用户配置文件
问题描述
所以我想做一个页面,让用户可以看到他们的一些细节。没有其他人可以看到此页面。
网址是
path('accounts/perfil/<int:pk>', views.Perfil.as_view()),
所以我需要检查登录的用户是否与url中的相同。如何使用基于类的视图来做到这一点?
解决方案
您不需要在 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
推荐阅读
- animation - 部分 SVG 在悬停时的动画变化
- java - 错误附加程序包含无效元素或属性“NoSql”
- azure - 我们如何向一个本地数据网关添加多个订阅?
- airflow - 使用“with dag as DAG(...)”子句创建 DAG 是否有好处
- reactjs - react-admin 展开 Unknown dataProvider 功能:getOne
- sql - 在将插入脚本生成为动态查询时,即使列是 nvarchar,此 N 也不会得到前缀
- google-sheets - 如何计算谷歌电子表格中的对称差异
- c - malloc 和 free 的内存管理
- python - 将相同值传递给参数的紧凑方法
- javascript - 如何向使用 for 循环呈现到页面的数组中的特定项目添加验证?