parse multiple values to user_passes_test in a function-based view

Viewed 100

I have a function-based view

#views.py

def my_view(request,pk):
   post = Posts.get(pk)
   .
   .
   .
    return redirect("my-view")

I want to make sure, that the user created the post, also is the one approaching the page.

In the class-based view we can define the test_func

class MyPosts(UserPassesTestMixin):


    def test_func(self):
        """
        Check if the logged in user is the one created the link
        """
        post= self.get_object() #Gets the current post
        if self.request.user == post.user:
            return True
        return False

but I cannot figure out how to parse the post argument (or the post.user) to the user_passes_test function in the function-based view. According to the documentation the user_passes_test decorator has to take a function which takes a User argument as the first arguemnt and two optional arguments - and I need to parse both the User and the post-user i.e two user objects and not 1 e.g something like

def my_test_func(User,post-user):
    if User==post-user:
       return True
    return False

How do I accomplish this w/o using a Class-based view as described above?

1 Answers

I think it makes more sense to check this in the view than in a decorator. In that case, we can use the .get_object_or_404(…) functin to check both the primary key and the author in the same query, so something like:

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404

@login_required
def my_view(request, pk):
    post = get_object_or_404(Post, pk=pk, user=request.user)
    # …
Related