Django模板在当前URL后添加GET参数

uplii1fm  于 2023-01-14  发布在  Go
关注(0)|答案(1)|浏览(140)

以前,我通过在URL上请求?lang=<lang_code>参数来处理我的翻译。

<h6>{% trans "Translate" %}</h6>
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<span id="language-icons">
  {% for language in languages %}
    {% if language.code == 'id' %}
      <a href="?lang=id" title="Indonesia">
        <img height="20px" src="{% static 'icons/flags/id.svg' %}">
      </a>
    {% elif language.code == 'en' %}
      <a href="?lang=en" title="English">
        <img height="20px" src="{% static 'icons/flags/us.svg' %}">
      </a>
    {% endif %}
  {% endfor %}
</span>

当我处理{{ request.META.QUERY_STRING }}时,
并且之前的URL已包含lang= param (例如:/path/to/?page=2&lang=en
下一个lang=将尝试多次 (例如:/path/to/?page=2&lang=en&lang=id
我想用新的lang=id替换旧的lang=en参数,所以url应该是/path/to/?page=2&lang=id
这是我所尝试的

{% with QUERY_STRING=request.META.QUERY_STRING %}
  {% if QUERY_STRING %}
    {% if 'lang' in QUERY_STRING %}
      <a href="?{{ QUERY_STRING|replace_with:"lang=id" }}">   <!-- something like `replacer` -->
    {% else %}
      <a href="?{{ QUERY_STRING }}?lang=id %}">...</a>
    {% endif %}
  {% else %}
    <a href="?lang=id">...</a>
  {% endif %}
{% endwith %}

我只是想,上面的问题可能很好的处理时,与模板标签,如:

@register.filter
def append_url_param(request, replacer='lang=id'):
    params = request.META.QUERY_STRING        # 'id=1&lang=en'
    replacer_list = replacer.split('=')

    if len(replacer_list) > 1:
        key = replacer_list[0]
        value = replacer_list[-1]

        if key in params:
            params = params.replace(????)
mwkjh3gx

mwkjh3gx1#

最后,我用urllib.parse库解决了这个问题:

from urllib import parse

@register.filter
def append_url_param(url, rep='lang=id'):
    """
    function to replace the query string of url.
    :param `url` is string full url or GET query params.
    :param `rep` is string replacer.
    """
    rep_list = rep.split('=')
    queries = url

    if len(rep_list) > 1:
        rep_key = rep_list[0]
        rep_val = rep_list[1]
    
        if 'http' in url:
            queries = parse.urlsplit(url).query

        dict_params = dict(parse.parse_qsl(queries))
        dict_params.update({rep_key: rep_val})

        queries_list = []

        for (k, v) in dict_params.items():
            queries_list.append('%s=%s' % (k, v))

        base_url_list = url.split('?')
        base_url = base_url_list[0]
        
        if len(base_url_list) <= 1:
            base_url = ''
        
        queries_str = '&'.join(queries_list)

        return '%s?%s' % (base_url, queries_str)

    return url

并用于模板中;

<a href="{{ request.META.QUERY_STRING|append_url_param:'lang=id' }}">...</a>

<a href="{{ request.META.QUERY_STRING|append_url_param:'lang=en' }}">...</a>

结果示例;

<a href="?page=1&q=abc&lang=id">...</a>

<a href="?id=3&lang=en">...</a>

控制台示例;

>>> url = 'http://127.0.0.1:8000/add-edit/?id=3&page=1&lang=en'
>>> append_url_param(url=url, rep='lang=id')
'http://127.0.0.1:8000/add-edit/?id=3&page=1&lang=id'
>>>
>>>
>>> url = 'id=3&page=1&lang=id'
>>> append_url_param(url=url, rep='lang=en')
'?id=3&page=1&lang=en'
>>>

相关问题