【问题标题】:How can I search variables from another template如何从另一个模板中搜索变量
【发布时间】:2020-01-18 09:13:08
【问题描述】:

我在我的主页模板中,我只有像谷歌主搜索页面这样的搜索框,现在我想从另一个模板中搜索变量并显示它,但没有任何反应。下面是我的代码

首页模板

<form action="{% url 'loststuffapp:IndexView' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;">
        <input type="text"placeholder="Search....." name="q">
        <button type="submit" onclick="/Miscellaneous"><i class="fa fa-search"></i></button>
</form>

主页视图

def IndexView(request):
    title="Homepage"
    return render(request, "loststuffapp/home.html", {"title":title})

其他模板

<div class="card-body">
  <p><label style="font-size:15px; font-weight: bold;color: black;">Jina la nyaraka:  </label>{{Doc.docs_name}}</p>
    <p><label style="font-size:15px; font-weight: bold;color: black;">Aina ya nyaraka:  </label>{{Doc.item_type}}</p>
    {% if Doc.image %}
 <div class="row">
    <div class="col-md-12">
       <img class="img-fluid" alt="Responsive image" src ="{{Doc.image.url}}" style="display: flex;" />
    </div>
 </div>

    {% endif %}
    <p>{{Doc.date}}</p>
</div>

其他视图

def Miscellaneous(request):
    query = request.GET.get('q', '')
    qsets=(Q(docs_name__icontains=query)|Q(item_type__icontains=query))
    return render(request, "loststuffapp/Miscellaneous.html", context={"documents":Documents.objects.filter(qsets)})

【问题讨论】:

    标签: javascript html django python-3.x


    【解决方案1】:

    如果我理解正确,您希望将 q 参数从主页上的表单传递到杂项视图。目前,您的代码只是在提交表单时调用您的 IndexView 并返回它。

    我猜您希望通过将 url 添加到按钮的onclick 来将表单提交到 Miscellaneous 视图。我认为这不会像onclick 需要一些javascript 函数那样工作。您的表单提交到您在表单的 action 属性中输入的 url,这就是您的主页。

    因此,最简单的方法是更改​​表单的 action 属性以指向您的 Miscellaneous 视图:

    <form action="{% url 'loststuffapp:Miscellaneous' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;">
            <input type="text"placeholder="Search....." name="q">
            <button type="submit"><i class="fa fa-search"></i></button>
    </form>
    

    备注:我不确定您对 value 属性或表单的期望

    您还可以做的是在提交表单时返回您的IndexView 并从那里重定向到MiscellaneaousView,将查询作为参数传递。但是,从我从您的帖子中读到的内容来看,这似乎没有必要。

    【讨论】:

    • 非常感谢它成功了,我真的很远,我没想到
    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2020-07-13
    相关资源
    最近更新 更多