链接到Django中的当前页面,还有其他GET参数?

时间:2011-06-20 17:12:14

标签: django url

如何放置指向当前页面的HTML链接,添加其他 GET参数(或覆盖现有参数)如果他们已经存在)?

现在我有类似的东西:

 <a href="{{ request.path }}?Key=Value"> My Link </a>

目前,request已传递到该页面。如果request.pathhttps://stackoverflow.com/,则生成的链接将变为https://stackoverflow.com/?Key=Value

问题?

但当然,如果当前网址为https://stackoverflow.com/?PrevKey=PrevValue,则会变为:

  

https://stackoverflow.com/?PrevKey=PrevValue?Key=Value

注意错误的第二个问号 - 实际上应该是:

  

https://stackoverflow.com/?PrevKey=PrevValue&Key=Value

此外,如果已经一个具有相同名称的密钥,那么我当前的解决方案忽略了它而不是覆盖它 - 这是错误的。

如何解决这两个问题?

4 个答案:

答案 0 :(得分:4)

您需要自定义标记。 djangosnippets上有一对 - this one看起来非常全面。

答案 1 :(得分:1)

对于将来看到这一点的人:https://bitbucket.org/monwara/django-url-tools

答案 2 :(得分:0)

您可以使用:{{request.get_full_path}}来获取包含其他参数的当前路径。

答案 3 :(得分:0)

我只是Django的初学者,所以你必须带着我的回答。

首先,根据documentationrequest.path应该返回没有域名的网页路径。因此,如果请求是http://example.com/request.path应该只是"/"。如我错了请纠正我。

但那不相关。更重要的是,request.path不会有任何查询参数,因此如果请求的网页为http://example.com/?PrevKey=PrevValue,则request.path仍为"/"。如果要获取查询参数,则必须使用request对象的GET和POST属性(在本例中为GET)的类字典访问。或者更好的是,通过QueryDict methods访问它们。

我在这里做的,这绝不是最好的方法,也不是代码,是准备一个自定义模板过滤器,在其中传递当前请求对象和要测试的键值对。

这是模板代码的外观。请注意,您仍然可以对键值对进行硬编码,尽管此处将其格式化为带有“键冒号值”的字符串。过滤器函数可以处理(如果需要)多于一组键值对。

<a href="{{ request | addQueryParameter:'Key:Value'}}">My Link</a>

过滤功能:

from urllib import urlencode

def addQueryParameter(request, parameter):
    # parse the key-value pair(s) in parameter (which looks like a JSON string)
    # then add to dictionary d
    # note i am not taking into account white-space.
    for param in string.split(','):
        key, value = param.split(':', 1)
        d[key] = value

    # check if any keys in d are already in the request query parameters
    # if so, delete from d. If I misunderstood your question, then refactor 
    # to delete from request.GET instead:
    for key in d.keys():
        if key in request.GET.keys():
             del d[key]

    # add the keys in request.GET into d:
    d.extend(request.GET.items())

    # convert dictionary of key value pairs into a query string for urls, 
    # prepend a ?
    queryString = "?%s" % urlencode(d)
    return "%s%s" % (request.path, queryString if queryString else "")

我应该指出,如果请求是针对页面http://example.com/login/?prev=news而您的模板看起来像

<a href="{{ request | addQueryParameter:'goto:dashboard,feature:products'}}">My Link</a>

然后输出(希望,如果它有效):

<a href="/login/?prev=news&goto=dashboard&feature=products">
My Link</a>
<!-- the order of the above parameters may differ -->

请注意,此链接中没有域(即http://example.com/部分)。那是因为过滤器不添加它。但你可以修改它来这样做。

我会留给你register this template filter。更多here。希望这会有所帮助。