【问题标题】:Django Error NoReverseMatch at / - Django Pattern No Match ErrorDjango 错误 NoReverseMatch at / - Django 模式不匹配错误
【发布时间】:2020-11-22 23:47:26
【问题描述】:

我在互联网上尝试了很多解决方案并尝试了很多 URL 模式,但都没有正常工作。这是我的 urls.py

urlpatterns = [
re_path(r'^category/(?P<cat>\w+)/$',views.categoryPage,name="category"),
re_path(r'^',views.home,name="index"),
]

html 链接

 <a class="nav-link" href='{% url "category" cat=mobiles %}'>Mobiles & Tablets <i class="fa fa-angle-down iconClr" aria-hidden="true"></i></a>

views.py

def categoryPage(request,cat):

    return render(request,'amazonApp/categoryItem.html',context={'category_name':cat})

浏览器出错

NoReverseMatch at /
Reverse for 'category' with keyword arguments '{'cat': ''}' not found. 1 pattern(s) tried: 
['category/<cat>']
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 3.0.8
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'category' with keyword arguments '{'cat': ''}' not found. 1 pattern(s) tried: 
['category/<cat>']
Exception Location: C:\Users\DELL\Django\amazon_affiliate\env\lib\site- 
packages\django\urls\resolvers.py in _reverse_with_prefix, line 677
Python Executable:   
C:\Users\DELL\Django\amazon_affiliate\env\Scripts\python.exe
Python Version: 3.8.5
]

我尝试了一种 Django Documentation 解决方案,但没有帮助。

【问题讨论】:

    标签: python python-3.x django django-views django-templates


    【解决方案1】:

    您需要将参数作为字符串文字传递给 url 标记

    {% url "category" cat='mobiles' %}
    

    您的上下文中没有名为 mobiles 的变量,因此当您使用 cat=mobiles 时,这将被解释为 cat=''

    【讨论】:

    • 你能解释一下吗?横向传递字符串是什么意思?请。你能写一点代码吗?
    • 你没有一个名为mobiles的变量,如果你想传递字符串'mobiles',你需要用引号括起来
    猜你喜欢
    • 2018-04-21
    • 2020-09-19
    • 1970-01-01
    • 2017-10-07
    • 2015-10-24
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多