未从 urls.patterns 调用视图函数

View function is not called from urls.patterns

我的视图函数未被 urls.py 模式调用。我只能明确地调用它们。

基本布局是

--project
----persons
----project

project/urls.py 是:

from django.conf.urls import url, include, patterns
from .views import page   #irrelevant
# from persons import views as person_views

urlpatterns = patterns('',
    url(r'^(?P<slug>[\w./-]+)/$', page, name='page'), #irrelevant
    url(r'^$', page, name='homepage'),                #irrelevant
    url(r'^persons/', include('persons.urls', namespace='persons')),  # WORKS
#   url(r'^persons/$', person_views.persons, name='persons'),   #wont work
#   url(r'^persons/add/$', person_views.add_person, name='add_person'),  #wont work
)

到目前为止一切正常,因为 persons.urls 已成功包含...但是里面:

persons/urls.py:

from django.conf.urls import patterns, url
#from persons.views import index_persons, add_person
from persons import views

#views.index_persons('GET / HTTP/1.0')  # >>> WORKS - function called <<< !!!

urlpatterns = patterns('',
    url(r'.', views.index_persons, name='index_persons'), # DOES NOT WORK
    url(r'^add/', views.add_person, name='add_person'),   # DOES NOT WORK
)

我也尝试过其他正则表达式,例如:

    url(r'*', views.index_persons, name='index_persons'), # DOES NOT WORK
    url(r'^$', views.index_persons, name='index_persons'), # DOES NOT WORK

运气不好...

我的 persons/views.py 文件包含:

def index_persons(request):
    print 'WHY???'

def add_person(request):
    print 'WHY???'

'WHY???' 通常在控制台中打印(stdout - 因为我从 manage.py runserver 执行),当显式调用 index_persons 函数时 来自 persons/urls.py

有什么想法吗?

你的 url 规则应该是

url(r'^/?$, views.index_persons, name='index_persons'), 

注意 1: 不要忘记重启服务器。

NOTE 2namespace='persons'等于不设置namespace,因为你的urlpersons/是一样的.

project/urls.py 中,将 page url 模式移动到其他模式下方。否则,对 /persons/ 的请求将首先匹配 page url 模式。

url(r'^$', page, name='homepage'),
url(r'^persons/', include('persons.urls', namespace='persons')),
url(r'^(?P<slug>[\w./-]+)/$', page, name='page'),

persons/urls.py里面,你应该有:

urlpatterns = patterns('',
    url(r'^$', views.index_persons, name='index_persons'),
    url(r'^add/$', views.add_person, name='add_person'),
)