在应用之间使用 Django url 模板标签

Using the Django url template tag between apps

我在 Django 1.8 中使用带有两个应用程序的命名空间 URLs。请参阅下面的简约结构:

购物车
- 模板
- -购物车
- - -购物车-template.html
- urls.py
- views.py
商店
- settings.py
- urls.py
产品
- 模板
- -购物车
- - -购物车-template.html
- urls.py
- views.py

所以我为 'main' 应用程序设置了路线:

#Shop/urls.py
urlpatterns = patterns(
    '',
    url(r'^cart/', include('cart.urls', namespace='cart')),
)

和购物车应用

#Cart/urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
]

此模板标签完美运行:

# Cart/templates/cart/cart-template.html
<form action= {% url 'cart:index' %} method="post">

但是,当我在产品页面(由产品应用程序处理)上并单击应该以完全相同的方式重定向我的按钮时,它会显示 404:

# Product/templates/product/product-template.html
<form action= {% url 'cart:index' %} method="post">

换句话说,我不能使用Cart应用的命名空间url,在另一个应用的模板中,Product.How我可以做这个possible/what我做错了吗? 这是我的输出:

Page not found (404)
Request Method:     GET
Request URL:    http://0.0.0.0:8000/cart/cart.views.index

似乎尝试使用应该调用的视图,作为URL。

编辑:当我在隐藏字段中添加名称属性时似乎发生了错误:

<!-- Product/templates/product/product-template.html -->

<form action= {% url 'cart:index' %} method="post">  
            {% csrf_token %}  
            <!-- this link works -->  
            <a href={% url 'cart:index'%}> Click</a>  
            <!-- Submit button goes to correct URL when name attribute of hidden field below is commented out, but I need it to know what to put in cart -->
            <input type="hidden" name="id" value="{{ article.id }}"> 
            <input type="submit" value="Bestellen" class="btn btn-default"/>
        </form>

删除隐藏输入字段的名称属性后,出现以下错误:

MultiValueDictKeyError at /cart/  

"'id'"

感谢您的努力。我发现了错误。在购物车的索引视图中,我曾经使用以下行:

return redirect(cart.views.index)

如果购物车被修改(文章被删除,或增加数量等),我用来重定向用户。重定向函数在内部使用 reverse() 函数,因此匹配该视图的 URL 将是解决。参见:https://docs.djangoproject.com/en/1.8/ref/urlresolvers/#reverse

对于命名视图,重定向函数无法使用 reverse() 函数,因此它无法将 cart.views.index 解析为输入,只是在不解析的情况下重定向到它。

我通过反转命名路由以获取 url 并像这样重定向用户来修复它:

return redirect(reverse('cart:index'))