2015-12-01 65 views
3

我得到這個錯誤:Django反向導致url循環導入,爲什麼?

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} 

我知道我可以用perfil/mi_perfil這樣的純文本網址替代reverse。但是,我想知道爲什麼會發生這種情況,我無法找到關於文檔的解釋。另外,使用reverse會更好,因爲它是動態的(如果我更改url,只要它保持其名稱,它仍然有效)。

回答

5

當導入視圖時可能會調用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} 
+0

謝謝,'reverse_lazy'是解決方案。所以..當導入視圖時,urlconf尚未加載? – alejoss

+0

你在你的urlconf中導入視圖...所以沒有。 – knbk