[Answer]-User_passes_test and Django

1👍

Well, you can use exists

if UserSubject.objects.filter(user=request.user, subject=subject).exists():
    # what you want to do
else:
    # do something else

or just filter

usersub = UserSubject.objects.filter(user=request.user, subject=subject)
if usersub:
    # do something
else:
    # do something else

Those will make your check but will not raise an Exception or return a Http404.

Update: You must write your own decorator, since user_passes_test can nor handle your situation. Here is an example decorator:

from django.http import HttpResponseForbidden

def subject_test(f, subject):
    def test_user_for_subject(request, subject, *args, **kwargs):
        if not UserSubject.objects.filter(user=request.user, subject=subject).exists():
            retun HttpResponseForbidden('Access denied!')
        else:
            return f(request, *args, **kwargs)
    return test_user_for_subject

An in your views :

@subject_test('your subject here')
def your_view_is_in_here(request):
    ...

But the hard part is, you must pass all your filter arguments unless they are reachable from request

👤Mp0int

Leave a comment