Redirect loop caused by django middleware

3.9k views Asked by At

I am trying to redirect users right after signup to go to a terms of agreement page.

This is my Middleware class:

class TermsMiddleware(object):

    def process_request(self, request):
        if request.user.profile.filled_terms is None:
            return redirect(reverse('terms')) 

I am getting the following error which I can confirm from a quick glance at my server:

This webpage has a redirect loop

I have a Profile model class with a filled_terms field.

I have a term template that is working just fine when I go to it manually.

Also here is my url matcher:

url(r'^terms/', 'hana.views.terms', name='terms')

How can I get out of this redirect loop and have users on signup be redirected with the middleware to terms of agreement page?

1

There are 1 answers

2
MichielB On

Well, also the requests to the terms page are processed, and if filled_terms is None, it redirects to the Terms page, which... and that is your loop.

So one way to go about this is to check in the middleware if the current request is for the path of the redirect page:

class TermsMiddleware(object):

    def process_request(self, request):
        if request.user.profile.filled_terms is None:
            if not request.path == reverse('terms'):
                return redirect(reverse('terms'))

That way you only perform a redirect if the request is not for the redirect page already.