Mickey Cheong Mickey Cheong - 1 year ago 54
Python Question

Django RedirectView and reverse() doesn't work together?

I'm having this weird problem.

When I did this:

from django.core.urlresolvers import reverse
# returns '/accounts/recommendations/about-you/'

But when I did this:

# Doesn't Work
recommendations = login_required(RedirectView.as_view(url=reverse('account-reco-about-you')))

# Work
recommendations = login_required(RedirectView.as_view(url='/accounts/recommendations/about-you'))

Error message I get if unrelated. It says my last view is not found, which is there. Any explanation? Meantime, i'll make do with the non-reverse style.


This problem is to do with trying to reverse something at import time before the URLs are ready to be reversed. This is not a problem with RedirectView itself - it would happen with anything where you tried to reverse in your urls.py file, or possibly in a file imported by it.

In the development version of Django, there is a function called reverse_lazy specifically to help in this situation.

If you're using an earlier version of Django, there is a solution here: Reverse Django generic view, post_save_redirect; error 'included urlconf doesnt have any patterns'.