使用Ajax POST的Django Urls和App URL

时间:2012-07-05 13:58:28

标签: ajax django urlconf

我发现了一个问题并将其追踪到url conf。我正在尝试在/ gallery / add页面上执行一个ajax帖子,这会在数据库中添加一条新记录。

最初我在我的应用程序中添加了一个urls.py然后从根urls.py'包含'但是在ajax帖子中失败了(出现/ gallery /刚从日志中返回)。

然后我恢复到根urls.py,它按预期工作。

所以问题是这些urlconf是等效的吗?

(A)

# ./urls.py
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^gallery$', 'gallery.views.home'),
    (r'^gallery/add$', 'gallery.views.add'), # ajax post works with this one
)

(B)

# ./urls.py
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^gallery/', include('gallery.urls')),
)

# ./gallery/urls.py
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'$', 'gallery.views.home'),
    (r'add$', 'gallery.views.add'), # ajax request doesn't work, instead it goes to gallery.views.home
)

1 个答案:

答案 0 :(得分:3)

在第二个示例中,您仍然需要^,否则第一个正则表达式将匹配任何具有结尾的旧字符串(由于$),这当然是所有这些:)

# ./gallery/urls.py
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^$', 'gallery.views.home'),
    (r'^add$', 'gallery.views.add'),
)