这是我在 Django 1.3 项目中的做法。像你一样,我希望找到这个内置的,但最终在视图中对其进行了编码:
def remove_url_param(url, params):
if not isinstance(params, list):
params = [params,]
if isinstance(url, unicode):
# urlencode doesn't like unicode
url = url.encode('utf8')
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(url)
param_dict = parse_qs(query)
for p in params:
try:
del(param_dict[p])
except KeyError:
pass
query = urllib.urlencode(param_dict, True)
return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
然后我用它来创建基本 URL:
page_url_unordered = putils.remove_url_param( request.get_full_path(), ['order', 'ajax'] )
然后在模板中:
<a href="{{ page_url_unordered }}&order=price">Price</a>
<a href="{{ page_url_unordered }}&order=size">Size</a>