Django 反向导致 url 循环导入,为什么?

Django reverse causing url circular import, why?

我收到这个错误:

The included urlconf 'fouraxis.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

我知道 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 视图如下所示:

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}

我知道我可以用这样的纯文本 url 替换 reverse perfil/mi_perfil。但是,我想知道为什么会发生这种情况,我在 de docs 上找不到解释。此外,使用 reverse 更好,因为它是动态的(如果我随时更改 url,只要保留其名称,它仍然有效)。

reverse() 调用是在导入视图时进行的,这可能是在首次加载 urlconf 时。您需要使用 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}