¿Django RedirectView y reverse () no funcionan juntos?

I'm having this weird problem.

Cuando hice esto:

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.

preguntado el 28 de agosto de 11 a las 01:08

4 Respuestas

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: Vista genérica inversa de Django, post_save_redirect; error 'urlconf incluido no tiene ningún patrón'.

contestado el 23 de mayo de 17 a las 15:05

Necesita usar "reverse_lazy" que está definido en "django.core.urlresolvers" en Django 1.4 y superior.

Aquí hay un ejemplo de 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'),

)

Entonces, en el ejemplo anterior, la URL "/ redirect-home" redirigirá a "/". Espero que esto ayude.

Respondido 07 ago 13, 19:08

With Django 2.1 from django.urls import reverse_lazy - Natim

no hay necesidad de reverse() or reverse_lazy().

simply specify the pattern_name parámetro:

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

Respondido 03 Feb 15, 00:02

pattern_name is available for v >= 1.6. However, in urls.py it doesn't seem to work for me... It returns 410 like when no url is specified. - Wtower

Didn't help in django 1.11 - holms

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

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

Respondido 09 Jul 16, 08:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.