如何使用查询args构造Django reverse / url? [英] How do I construct a Django reverse/url using query args?
问题描述
我有一些网址,如 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 smiles = input_smiles width = 200 height = 200%}
其中input_smiles是通过for for输入到模板在这种情况下,它是字符串CO,我认为它会创建一个像顶部的URL。
此模板失败并显示TemplateSyntaxError: p>
渲染时捕获异常:使用参数'()'和关键字arguments'{'smiles':u' CO','height':200,'width':200}未找到。
这是一个相当常见的错误消息这里是StackOverflow和其他地方。在每种情况下,我发现人们正在使用它们的URL路径regexp中的参数,这不是我有参数进入查询的情况。
这意味着我做错了我该怎么做?也就是说,我想使用模板中的东西来构建完整的URL,包括路径和查询参数。
为了参考,
%python manage.py shell
Python 2.6.1(r261:67515,2010年2月11日00:51:29)
[GCC darwin
4.2.1(Apple Inc. build 5646)]更多信息,请输入help,copyright,credits或license。
(InteractiveConsole)
>>>来自django.core.urlresolvers import reverse
>>>> reverse(cyclops-depict,kwargs = dict())
'/ depict'
>>> reverse(cyclops-depict,kwargs = dict(smiles =CO))
追溯(最近的最后一次调用):
文件< console>,第1行,< module> ;
文件/Library/Python/2.6/site-packages/django/core/urlresolvers.py,第356行,反向
* args,** kwargs))
文件 /Library/Python/2.6/site-packages/django/core/urlresolvers.py,第302行,反向
arguments'%s'not found。 %(lookup_view_s,args,kwargs))
NoReverseMatch:反转为'cyclops-depict'与参数'()'和关键字参数'{'微笑':'CO'}'未找到。
你的常规表达没有占位符(这就是为什么你得到NoReverseMatch):
url(r'^ depict $',cyclops.django.depict,name =cyclops-depict ),
您可以这样做:
{%url cyclops-depict%}?smiles = CO& width = 200& height = 200
或者如果您希望使用{%url%}标签,则应重新构建您的网址格式像
r'^描绘/(?P< width> \d +)/(?P< height> \\ d +)/(?P< smiles> \w +)$'
那么你可以做某事像
{%url cyclops-depict 200 200CO%}
/ pre>
后续行动:
自定义标签的简单示例:
from django.core.urlresolvers import reverse
from django import template
register = template.Library()
@ register.tag(name =myurl)
def myurl(解析器,令牌):
tokens = token.split_contents )
return MyUrlNode(tokens [1:])
class MyUrlNode(template.Node):
def __init __(self,tokens):
self.tokens =
def render(self,context):
url = reverse('cyclops-depict')
qs ='&'。join([t for t in self.tokens])
return'?'。join((url,qs))
您的模板中的标签如下所示:
{%myurl width = 200 height = 200 name = SomeName%}
,希望它应该输出像
?code> /描绘宽度= 200安培;高度= 20 0& name = SomeName
I have URLs like http://example.com/depict?smiles=CO&width=200&height=200 (and with several other optional arguments)
My urls.py contains:
urlpatterns = patterns('', (r'^$', 'cansmi.index'), (r'^cansmi$', 'cansmi.cansmi'), url(r'^depict$', cyclops.django.depict, name="cyclops-depict"),
I can go to that URL and get the 200x200 PNG that was constructed, so I know that part works.
In my template from the "cansmi.cansmi" response I want to construct a URL for the named template "cyclops-depict" given some query parameters. I thought I could do
{% url cyclops-depict smiles=input_smiles width=200 height=200 %}
where "input_smiles" is an input to the template via a form submission. In this case it's the string "CO" and I thought it would create a URL like the one at top.
This template fails with a TemplateSyntaxError:
Caught an exception while rendering: Reverse for 'cyclops-depict' with arguments '()' and keyword arguments '{'smiles': u'CO', 'height': 200, 'width': 200}' not found.
This is a rather common error message both here on StackOverflow and elsewhere. In every case I found, people were using them with parameters in the URL path regexp, which is not the case I have where the parameters go into the query.
That means I'm doing it wrong. How do I do it right? That is, I want to construct the full URL, including path and query parameters, using something in the template.
For reference,
% 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.
解决方案Your regular expresion has no place holders (that's why you are getting NoReverseMatch):
url(r'^depict$', cyclops.django.depict, name="cyclops-depict"),
You could do it like this:
{% url cyclops-depict %}?smiles=CO&width=200&height=200
URLconf search does not include GET or POST parameters
Or if you wish to use {% url %} tag you should restructure your url pattern to something like
r'^depict/(?P<width>\d+)/(?P<height>\d+)/(?P<smiles>\w+)$'
then you could do something like
{% url cyclops-depict 200 200 "CO" %}
Follow-up:
Simple example for custom tag:
from django.core.urlresolvers import reverse from django import template register = template.Library() @register.tag(name="myurl") def myurl(parser, token): tokens = token.split_contents() return MyUrlNode(tokens[1:]) class MyUrlNode(template.Node): def __init__(self, tokens): self.tokens = tokens def render(self, context): url = reverse('cyclops-depict') qs = '&'.join([t for t in self.tokens]) return '?'.join((url,qs))
You could use this tag in your templates like so:
{% myurl width=200 height=200 name=SomeName %}
and hopefully it should output something like
/depict?width=200&height=200&name=SomeName
这篇关于如何使用查询args构造Django reverse / url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!