Django- NoReverseMatch。反向''带参数'(2,)'和关键字参数'{}'未找到。尝试过0种模式:[]

时间:2015-03-19 23:28:08

标签: python django django-templates

我试图将模板文件中的值传递给Django中views.py文件中的函数。

我的项目结构如下 -

myproject/
    manage.py
    myproject/
        __init__.py
        urls.py
        wsgi.py
        views.py
        settings.py
    orders/
        __init__.py
        models.py
        views.py
        urls.py
        tests.py
    restaurant/
        __init__.py
        models.py
        views.py
        urls.py
        tests.py

     requirements.txt

这是我的templates/menu.html文件 -

...
...    
{% for id,image,menu in imageList %}
    <div style = "display:inline-block">
        <img src="{{ MEDIA_URL }}{{ image }}">
        <p>{{ menu }}</p>
        <a href="{% url 'addCart' id %}">+</a>
        <a href="">-</a>
    </div>
{% endfor %}
...
...

orders/urls.py是 -

....
from orders.views import add_to_cart

urlpatterns = patterns('',
    url(r'^add/(?P<product_id>\d+)$', add_to_cart, name ='addCart'),
)

urls.py是 -

from orders.views import *

urlpatterns = patterns('',
    url(r'^$', menu),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^orders/', include('orders.urls', namespace = "addCart")),
)

最后,orders/views.py如下 -

def add_to_cart(request, product_id):
    product = Inventory.objects.get(id=product_id)
    ....

执行此操作时,调用menu.html页面的主页会显示错误 -

Reverse for 'addCart' with arguments '(2,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

它表示错误发生在模板渲染过程中,特别是在行 -

<a href="{% url 'addCart' id %}">+</a>

我尝试了很多不同的解决方案,但似乎没有任何效果。 我也尝试在代码中使用orders:addCart。认为它没有用。是因为我从orders应用导入的视图格式错误了吗?谢谢。

1 个答案:

答案 0 :(得分:5)

您的网址位于名称空间'addCart'中,因此您在撤消网址时必须指定:

{% url 'addCart:addCart' id %}