改变url(Django)中的一个查询参数 [英] Altering one query parameter in a url (Django)

查看:127
本文介绍了改变url(Django)中的一个查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索页面需要各种参数。我想通过更改查询中的一个参数来创建一个新的URL。有没有一个简单的方法来做到这一点,例如:

 #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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆