更改 url (Django) 中的一个查询参数 [英] Altering one query parameter in a url (Django)
问题描述
我有一个采用各种参数的搜索页面.我想通过更改查询中的一个参数来创建一个新 URL.有没有一种简单的方法可以做到这一点 - 比如:
# 示例请求 urlhttp://example.com/search?q=foo&option=bar&option2=baz&change=before# 理想的模板代码{% url_with change 'after' %}# 结果网址http://example.com/search?q=foo&option=bar&option2=baz&change=after
所以这将获取请求 url,更改一个查询参数,然后返回新的 url.类似于在 Perl 的 Catalyst 中使用 $c->uri_with({change => 'after'})
可以实现的功能.
或者有更好的方法吗?
[更新:删除了对分页的引用]
所以,围绕这个写一个模板标签:
from urlparse import urlparse, urlunparse从 django.http 导入 QueryDictdef replace_query_param(url, attr, val):(scheme, netloc, path, params, query, fragment) = urlparse(url)query_dict = QueryDict(query).copy()query_dict[attr] = val查询 = query_dict.urlencode()返回 urlunparse((scheme, netloc, path, params, query, fragment))
要获得更全面的解决方案,请使用 Zachary Voase 的 URLObject 2,做得非常好.>
注意:urlparse
模块在 Python 3 中重命名为 urllib.parse
.
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.
Note:
The urlparse
module is renamed to urllib.parse
in Python 3.
这篇关于更改 url (Django) 中的一个查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!