我有类似http://example.com/depict?smiles=CO&width=200&height=200的网址(以及其他几个可选参数)
我的 urls.py 包含:
urlpatterns = patterns('',
(r'^$', 'cansmi.index'),
(r'^cansmi$', 'cansmi.cansmi'),
url(r'^depict$', cyclops.django.depict, name="cyclops-depict"),
我可以访问该 URL 并获取构建的 200x200 PNG,因此我知道该部分有效。
在来自“cansmi.cansmi”响应的模板中,我想在给定一些查询参数的情况下为命名模板“cyclops-depict”构建一个 URL。我以为我能做到
{% url cyclops-depict 微笑=input_smiles 宽度=200 高度=200 %}
其中“input_smiles”是通过表单提交对模板的输入。在这种情况下,它是字符串“CO”,我认为它会创建一个类似于顶部的 URL。
此模板因 TemplateSyntaxError 而失败:
渲染时遇到异常:未找到带有参数“()”和关键字参数“{'smiles': u'CO', 'height': 200, 'width': 200}' 的“cyclops-depict”的反向。
这是 StackOverflow 和其他地方的一个相当常见的错误消息。在我发现的每种情况下,人们都将它们与 URL 路径正则表达式中的参数一起使用,而我没有将参数放入查询中的情况。
这意味着我做错了。我该怎么做?也就是说,我想使用模板中的某些内容构建完整的 URL,包括路径和查询参数。
以供参考,
% python manage.py shell
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.urlresolvers import reverse
>>> reverse("cyclops-depict", kwargs=dict())
'/depict'
>>> reverse("cyclops-depict", kwargs=dict(smiles="CO"))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.6/site-packages/django/core/urlresolvers.py", line 356, in reverse
*args, **kwargs)))
File "/Library/Python/2.6/site-packages/django/core/urlresolvers.py", line 302, in reverse
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'cyclops-depict' with arguments '()' and keyword arguments '{'smiles': 'CO'}' not found.