[Django]-How can I write a decorator in Django to check two separate conditions and redirect accordingly?

5πŸ‘

βœ…

I don’t think you are helping yourself by trying to use the user_passes_test decorator. You would find this much easier if you created the decorator from scratch yourself.

def profile_required(view_func):
    def wrapped(request, *args, **kwargs):
        if request.user.is_anonymous():
            path = request.build_absolute_uri()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, LOGIN_URL)
        else:
            try:
                profile = request.user.profile
            except Profile.DoesNotExist:
                return redirect(CREATE_PROFILE_REDIRECT_URL)
            else:
                return view_func(request, *args, **kwargs)
    return wrapped

0πŸ‘

this should work

from functools import wraps

def profile_required(view_func):
  def _decorator(request, *args, **kwargs):
    if request.user.is_anonymous():
        return redirect(LOGIN_URL)
    else:
        try:
            profile = Profile.object.get(user=request.user)
        except Profile.DoesNotExist:
            return redirect('userprofile_url')

    response = view_func(request, *args, **kwargs)

    return response
return wraps(view_func)(_decorator)


@profile_required
def your_func(request):
   # do something
πŸ‘€phourxx

Leave a comment