django偶尔会抛出NoReverseMatch

时间:2015-06-03 22:36:42

标签: regex django django-urls

我在django模板渲染中偶尔出现错误;我有时在以下网址上获得NoReverseMatch:

    url(r'^student-agreement/(?P<code>[\w:-]+)$',
        StudentAgreementView.as_view(),
        name='student-agreement'),

code参数是通过在对象ID上调用signing.dumps()创建的,这会创建一个字符串,例如'MjExMg:1Z0H6s:1H19SjhO2CCAlAUgkiYLvyYLSzI' - 据我所知,这应该与提供的正则表达式匹配。但是,尝试类似的测试:

for i in range(20)
    print reverse('student-agreement', kwargs={'code':signing.dumps(i)})

会很快抛出NoReverseMatch。

以下是Traceback示例:

Traceback (most recent call last):
  File "/home/vagrant/.virtualenvs/sis_esv_repo/local/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2883, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-58-f02835044aa6>", line 2, in <module>
    print reverse('student-agreement', kwargs={'code':signing.dumps(i)})
  File "/home/vagrant/.virtualenvs/sis_esv_repo/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 551, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "/home/vagrant/.virtualenvs/sis_esv_repo/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 468, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'student-agreement' with arguments '()' and keyword arguments '{'code': 'Mg:1Z0H9L:ltHc7mAAteN7jBHRBIuT-Zbzt18'}' not found. 1 pattern(s) tried: ['school/student-agreement/(?P<code>[\\w:-_]+)$']

2 个答案:

答案 0 :(得分:0)

事实证明我在运行测试时使用的正则表达式与我在问题中发布的正则表略有不同 - 我没有重新加载我的实例,它使用的是我以前使用的旧正则表达式:{{1 }}。正确的正则表达式是(?P<code>[\w:-_]+) - (?P<code>[\w:-]+)使正则表达式匹配范围从:到_但不包括连字符本身。正确的正则表达式在集合的末尾连接,因此它被视为连字符。由于:-_包含下划线,因此下划线不是必需的,但\w也是正确的正则表达式。

感谢@fasouto指出我正确的方向!

答案 1 :(得分:-1)

输出也会生成_个字符。