我收到此错误:
我知道url模式中包含一些内容,看起来像这样:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^perfil/', include('clientes.urls'), namespace="cliente"),
url(r'^admin/', include(admin.site.urls))
]
clientes.urls:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from clientes import views
urlpatterns = [
# login
url(r'^login/$', auth_views.login, {'template_name': 'perfiles/login.html'}, name="login"),
url(r'^logout/$', auth_views.logout, {'template_name': 'perfiles/logged_out.html'}, name="login"),
url(r'^mi_perfil/$', views.mi_perfil, name="mi_perfil"),
url(r'^registro_usuario/$', views.RegistroUsuario.as_view(), name="registro_usuario")
]
RegistroUsuario View 如下所示:
class RegistroUsuario(FormView):
template_name = "perfiles/registro_usuario.html"
form_class = UserCreationForm
success_url = reverse("cliente:mi_perfil") # THIS REVERSE
def form_valid(self, form):
return redirect("cliente:mi_perfil")
context = {'form': UserCreationForm}
我知道我可以将
reverse
替换为像perfil/mi_perfil
这样的纯文本网址。但是,我想知道为什么反向发生这种情况,我无法在de docs上找到解释。另外,使用反向更好,因为它是动态的(如果我随时更改url,只要保留其名称,它仍然可以工作)。 最佳答案
导入 View 时(可能是首次加载urlconf时)进行reverse()
调用。您需要改用reverse_lazy()
:
from django.core.urlresolvers import reverse_lazy
class RegistroUsuario(FormView):
template_name = "perfiles/registro_usuario.html"
form_class = UserCreationForm
success_url = reverse_lazy("cliente:mi_perfil") # THIS REVERSE
def form_valid(self, form):
return redirect("cliente:mi_perfil")
context = {'form': UserCreationForm}
关于django - Django反向导致URL循环导入,为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34031818/