【问题标题】:NoReverseMatch error when using Django url template tag with optional parameters, but NOT when visiting the URL in the browser使用带有可选参数的 Django url 模板标记时出现 NoReverseMatch 错误,但在浏览器中访问 URL 时不会出错
【发布时间】:2014-08-11 12:54:22
【问题描述】:

我的 URL 需要考虑以下模式:

  • localhost:8000/staffing-agencies
  • localhost:8000/staffing-agencies/90210(邮政编码)
  • localhost:8000/staffing-agencies/portland-or (city-state)

当我在浏览器中输入这些网址中的任何一个时,它们都会按预期工作。但是,当我尝试从 Django 的 url 模板标签中引用此 URL 时,我收到了 NoReverseMatch 错误。

这是我的相关 url.py 文件:

# From urls.py
urlpatterns = patterns('',
    url(r'^', include('bos.apps.search.urls', namespace='search',
                       app_name='search')),
)

# From search/urls.py
urlpatterns = patterns('bos.apps.search',
    url(r'^staffing-agencies/'
        r'((?P<city>[a-zA-Z]+)-(?P<state>[a-zA-Z]{2}))?'
        r'((?P<zip>[0-9]{5}))?$',
        'views.main', name='main'),
)

我认为这可能与可选参数有关,但所有这些差异都会引发 NoReverseMatch 错误:

<a href="{% url "search:main" zip=97214 %}">Test</a>
<a href="{% url "search:main" city="portland" state="or" %}">Test</a>

这种差异不会引发错误:

<a href="{% url "search:main" %}">Test</a>

我正在使用 Django 1.6.5

【问题讨论】:

    标签: python django url django-templates


    【解决方案1】:

    这不是更好的解决方案,这是解决方案之一

    url(r'^staffing-agencies/(?P<city>[a-zA-Z]+)*-(?P<state>[a-zA-Z]{2})*?(?P<zip>[0-9]{5})*?$',
            'views.main', name='main'),
    

    在视图中:

    def main(request, city=None, state=None, zip=None):
    

    在 html 中:

    <a href="{% url "search:main"  city='sadasd' state='ds' zip=12345 %}">Test</a>
    

    在这种情况下,网址是这样工作的,

    • localhost:8000/staffing-agencies
    • localhost:8000/staffing-agencies/-90210(邮政编码)
    • localhost:8000/staffing-agencies/portland-or (city-state)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-28
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多