Home > database >  how to pass view method param to user passes test in django?
how to pass view method param to user passes test in django?

Time:12-24

i have a view method such as

@login_required(login_url='/users/login')
def my_submission(request,submission_id):

    submission = Submission.objects.get(pk=submission_id)

    return render(request, "assignments/mysubmission.html", {
            "submission": submission
        })

I was wondering if there is a way to pass submission_id which is the second param to user passes test decorator so that i can do something like

@user_passes_test(lambda u: u.id == Submission.objects.get(pk=submission_id).user.id, login_url='/')

thanks for the guide in advance.

CodePudding user response:

You should just write it as a check in the view:

@login_required(login_url='/users/login')
def my_submission(request,submission_id):

    submission = Submission.objects.get(pk=submission_id)
    if submission.user_id != request.user.pk:
        return redirect('/')

    return render(request, "assignments/mysubmission.html", {
            "submission": submission
        })

Update

If you use this many times, consider implementing it is a class-based view, so you could inherit and utilize some extra features:

class UserIsOwnerMixin(AccessMixin):
    """Verify that the user the owner of related object."""
    owner_id_field = 'user_id'

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or getattr(self.get_object(), self.owner_field) != request.user.pk:
            return self.handle_no_permission()

        return super().dispatch(request, *args, **kwargs)


class SubmissionView(UserIsOwnerMixin, DetailView):
    template = "assignments/mysubmission.html"
    model = Submission
    context_object_name = "submission"
    login_url = '/users/login'
    
    
  • Related