【问题标题】:How to add URL component to current URL via a HTML button? (Django 2.1)如何通过 HTML 按钮将 URL 组件添加到当前 URL? (Django 2.1)
【发布时间】:2019-07-03 00:57:51
【问题描述】:

我有一个 HTML 按钮,应该按字母顺序对搜索结果进行排序。

按钮 HTML 代码:

<a href="?a-z=True" type="button" class="btn btn-outline-{% if 'a-z' in request.GET %}success{% else %}secondary{% endif %}">A-Z</a>

views.py:

def query_search(request):
    articles = cross_currents.objects.all()
    search_term = ''
    if 'keyword' in request.GET:
        search_term = request.GET['keyword']
        articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity')
    if request.GET.get('a-z') == 'True':
        articles = articles.order_by('Title')

目前,URL 包含用户搜索的关键字。例如,如果用户搜索“奶酪”,则 URL 将为 search/?keyword=cheese。当我单击排序按钮时,URL 变为search/?a-z=True 并丢失了关键字,这意味着排序机制没有根据关键字对搜索结果进行排序。我想我需要 URL 同时包含关键字和?a-z=True,以便排序机制在搜索结果上起作用。我怎样才能做到这一点?

【问题讨论】:

    标签: django python-3.x


    【解决方案1】:

    我认为这不仅仅针对 Django,您可以使用 javascript 来做到这一点:

    添加一个函数,该函数将获取当前 url 并执行排序函数并通过 onclick 调用该函数。 然后添加必要的参数。

    <a href="#"  onclick="sort('a-z=True')"type="button" class="btn btn-outline-{% if 'a-z' in request.GET %}success{% else %}secondary{% endif %}">A-Z</a>
    

    然后在你的js部分,你可以检查url是否包含keyword参数,如果没有,只需添加排序参数。

    function sort(foo) {
        let url = window.location.href;
    
        // check if current url includes a "keyword" param else add the sort as param
        if(url.includes("?") && url.includes("keyword")) window.location.href = url + "&" + foo;
        else window.location.href = url + "?" + foo;
    }
    

    这只是一个想法,可能行不通,因为我从未尝试过运行它。

    【讨论】:

      猜你喜欢
      • 2015-01-27
      • 2012-01-23
      • 1970-01-01
      • 2019-01-20
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多