改变url(Django)中的一个查询参数 [英] Altering one query parameter in a url (Django)
问题描述
#example request url
http:// example。 com / search?q = foo& option = bar& option2 = baz& change = before
#理想的模板代码
{%url_with'''''%'
#produce url
http://example.com/search?q=foo&option=bar&option2=baz&change=after
所以这将需要url,更改一个查询参数,然后返回新的url。类似于Perl的Catalyst使用 $ c-> uri_with({change =>'after'})
。
还是有更好的方法?
[UPDATED:删除对分页的引用]
所以,写一个模板标签:
from urlparse import urlparse,urlunparse
from django.http import QueryDict
def replace_query_param(url,attr,val):
(scheme,netloc,path,params,query,fragment)= urlparse(url)
query_dict = QueryDict(query).copy()
query_dict [attr] = val
query = query_dict.urlencode()
return urlunparse((scheme,netloc,path,params ,查询,片段))
要获得更全面的解决方案,请使用Zachary Voase的 URLObject 2 ,这是非常好的。
I have a search page that takes a variety of parameters. I want to create a new URL by just altering one parameter in the query. Is there an easy way to do this - something like:
# example request url
http://example.com/search?q=foo&option=bar&option2=baz&change=before
# ideal template code
{% url_with change 'after' %}
# resulting url
http://example.com/search?q=foo&option=bar&option2=baz&change=after
So this would take the request url, alter one query parameter and then return the new url. Similar to what can be achieved in Perl's Catalyst using $c->uri_with({change => 'after'})
.
Or is there a better way?
[UPDATED: removed references to pagination]
So, write a template tag around this:
from urlparse import urlparse, urlunparse
from django.http import QueryDict
def replace_query_param(url, attr, val):
(scheme, netloc, path, params, query, fragment) = urlparse(url)
query_dict = QueryDict(query).copy()
query_dict[attr] = val
query = query_dict.urlencode()
return urlunparse((scheme, netloc, path, params, query, fragment))
For a more comprehensive solution, use Zachary Voase's URLObject 2, which is very nicely done.
这篇关于改变url(Django)中的一个查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!