How can I redirect in django middleware? global name 'view' is not defined

5.9k views Asked by At

Django newbie here, need help on basic middleware to redirect to another view if a certain model field is empty.

I am creating a terms of agreement page that users must get redirected to right after they signup to the platform if their filed_terms field on their Profile model is empty.

I am using middleware for this. However I am unable to get this to work. 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)) 

This gives me the following error:

global name 'terms' is not defined

I also have the url matcher that works perfectly when I navigate to it manually:

url(r'^terms/', 'my_app.views.terms')

I have a terms.html template and a terms view in my views.py file that is working perfectly in all other respects. I have also added it to the settings middleware requirements to make sure it loads.

Do I have to import something from views or url dispatcher into my middleware file? If so what would that be? I have been at this for a while an cannot find anything helpful.

1

There are 1 answers

4
Edwin Lunando On

reverse function takes url name instead on the regex. So you need to add name on your url configuration. Here is the example.

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

Add this in your views.py

from django.core.urlresolvers import reverse

And you need to fix your reverse function into.

return redirect(reverse('terms'))

Python interpret your terms as a variable and you have no variable named terms while you need to put string on reverse.