更改URL中的一个查询参数(Django)

Evd*_*vdB 17 django django-templates

我有一个搜索页面,其中包含各种参数.我想通过改变查询中的一个参数来创建一个新的URL.有没有一种简单的方法可以做到这一点 - 例如:

# 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
Run Code Online (Sandbox Code Playgroud)

因此,这将获取请求URL,更改一个查询参数,然后返回新的URL.类似于在Perl的Catalyst中可以实现的$c->uri_with({change => 'after'}).

或者,还有更好的方法?

[更新:删除了对分页的引用]

mpa*_*paf 19

我做了这个简单的标签,不需要任何额外的库:

@register.simple_tag
def url_replace(request, field, value):

    dict_ = request.GET.copy()

    dict_[field] = value

    return dict_.urlencode()
Run Code Online (Sandbox Code Playgroud)

用于:

<a href="?{% url_replace request 'param' value %}">
Run Code Online (Sandbox Code Playgroud)

它会在你的url GET字符串中添加'param',如果它不存在,或者如果它已经存在则用新值替换它.

您还需要从视图中将RequestContext请求实例提供给模板.更多信息:

http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/

  • 太好了!当你使用`takes_context = True`时,可以通过`context ['request']`读取请求,假设你正在使用`RequestContext`! (2认同)

Tom*_*tie 15

所以,围绕这个写一个模板标签:

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))
Run Code Online (Sandbox Code Playgroud)

要获得更全面的解决方案,请使用Zachary Voase的URLObject 2,这是非常好的完成.


whn*_*ode 10

我改进了mpaf的解决方案,直接从标签获取请求.

@register.simple_tag(takes_context = True)
def url_replace(context, field, value):
    dict_ = context['request'].GET.copy()
    dict_[field] = value
    return dict_.urlencode()
Run Code Online (Sandbox Code Playgroud)