如何阻止django中其他登录用户的页面访问?



我试图阻止登录用户访问其他用户更新配置文件页面。

我的情况:

假设A登录到他的个人资料,并且他知道其他用户更新个人资料的URl。在这种情况下,他可以简单地访问其他用户的更新配置文件url。所以,这里我想限制这个限制,只对同一个登录用户更新他们的个人资料。

这是我更新配置文件的代码:

@login_required
def UpdateProfile(request, slug):
user = Profile.objects.get(slug=slug)
if request.method == "POST":
form = UpdateProfileForm(request.POST, request.FILES, instance=user)
if form.is_valid():
profile_pic = form.cleaned_data['profile_pic']
form.profile_pic = profile_pic
form.save()
messages.success(request,"Data Updated successfully")
return HttpResponseRedirect(reverse('updateaddress', args=(request.user.profile.slug,)))
else:
messages.error(request, "Please check all fields are valid")
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
form = UpdateProfileForm(instance=user)
context = {
'user':user,
'form':form,
}
return render(request, "authentication/register/update/profile.html",context)

urls . py

path("<slug:slug>/update-profile/", UpdateProfile, name="updateprofile"),

你可以这样做:

@login_required
def UpdateProfile(request, slug):
user = Profile.objects.get(slug=slug)

if user.id == request.user.id:
# do something if the id of user you get from the slug matches the actual user id
if request.method == "POST":
form = UpdateProfileForm(request.POST, request.FILES, instance=user)
if form.is_valid():
# yada yada yada

您可以像下面这样比较用户对象

@login_required
def UpdateProfile(request, slug):
user = Profile.objects.get(slug=slug)
if user != request.user:
message.info("You can't update the other user profile")
return

在django文档中有如下描述https://docs.djangoproject.com/en/4.0/topics/db/queries/comparing-objects

你可以尝试像这样在

中作为装饰符
def verify_user_profile(view_func):
def wrapper_func(request, *args, **Kwargs):
user = Profile.objects.get(slug=args[0])
if user != request.user:
return
else:
return view_func(request, *args, **Kwargs)
return wrapper_func

视图调用将是:-

@verify_user_profile
@login_required
def UpdateProfile(request, slug):
...
...

相关内容

  • 没有找到相关文章

最新更新