Mickey Cheong
Mickey Cheong

Reputation: 3010

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

I'm having this weird problem.

When I did this:

from django.core.urlresolvers import reverse
reverse('account-reco-about-you')
# 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.

Upvotes: 13

Views: 9827

Answers (4)

taoxuau
taoxuau

Reputation: 61

@wtower pattern_name will be ok, but you may need to add namespace as below.

RedirectView.as_view(pattern_name='polls:index')

Upvotes: 3

captnswing
captnswing

Reputation: 645

no need for reverse() or reverse_lazy().

simply specify the pattern_name parameter:

RedirectView.as_view(pattern_name='account-reco-about-you')

Upvotes: 8

Alan Viars
Alan Viars

Reputation: 3162

You need to use "reverse_lazy" that is defined in "django.core.urlresolvers" in Django 1.4 and above.

Here is an example urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('apps.website.views',
    url(r'^$', 'home', name='website_home'),
    url(r'^redirect-home/$', RedirectView.as_view(url=reverse_lazy('website_home')), 
        name='redirect_home'),

)

So in the above example, the url "/redirect-home" will redirect to "/". Hope this helps.

Upvotes: 9

Duncan Parkes
Duncan Parkes

Reputation: 1953

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'.

Upvotes: 14

Related Questions