Home > OS >  How to block page access to other logged in user in django?
How to block page access to other logged in user in django?

Time:10-21

I am trying to block logged in user to access other user update profile page.

My situation:

Suppose Person A is logged in to his profile and he know other user update profile URl. In this situation he can simple getting access of the update profile url of other user. So , here i want to limit this restriction only to the same logged in user to update their profile only.

this is my code for updating profiles:

@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"),

CodePudding user response:

You can just do like this:

@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

CodePudding user response:

You can compare the user object like below

@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

As described here in django documents :- https://docs.djangoproject.com/en/4.0/topics/db/queries/#comparing-objects

  • Related