Home > Software design >  Check for a certain condition before processing each view in Django
Check for a certain condition before processing each view in Django

Time:04-26

I'm building a multi-tenant Django app, where I need to check for a certain condition before processing each view, similar to the login_required decorator which checks if user is authenticated or not.

And if the condition is not true, stop processing the view and send the user to the login page.

How can I implement this for each view in my app

My condition -

def index_view(request):
    domain1 = Domain.objects.get(tenant=request.user.client_set.first())
    domain2 = request.META["HTTP_HOST"].split(":")[0]

    # Condition
    if str(domain1) != domain2:
        return redirect("accounts:login")

    return render(request, "dashboard/index.html")

CodePudding user response:

You can use @user_passes_test decorator just like in the code below

create a method called condition_to_fulfil(user)

def condition_to_fulfil(user):
    # enter condition here
    if user_meets_condition:
        return True
    else:
        return False

Add the decorator above your view just like this

@login_required
@user_passes_test(condition_to_fulfil, login_url="/login/")
def index_view(request):
    domain1 = Domain.objects.get(tenant=request.user.client_set.first())
    domain2 = request.META["HTTP_HOST"].split(":")[0]

CodePudding user response:

You can create a decorator which do this job for you

def check_domain(func):
    def wrapper(request, *args, **kwargs):
        domain1 = Domain.objects.get(tenant=request.user.client_set.first())
        domain2 = request.META["HTTP_HOST"].split(":")[0]
        # Condition
        if str(domain1) != domain2:
           return redirect("accounts:login")
        return func(request, *args, **kwargs)
    return wrapper

@check_domain
def index_view(request):
    return render(request, "dashboard/index.html")

read more about decorators here.

  • Related