提交搜索表单后,无法通过Flask应用从网址检索变量 [英] Can't retrieve variable from url with Flask app after submitting search form

查看:47
本文介绍了提交搜索表单后,无法通过Flask应用从网址检索变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户提交搜索表单后,我想展示一个新视图.我用与其他视图相同的方法来完成此操作,但是不幸的是,这次没有任何反应,我无法从应用程序路线中检索内容. (因此,此问题不是 this的重复问题,该问题仅在提交表单后才会发生,它在其他情况下都可以正常使用.)我在表单中写了一些东西,然后提交,然后浏览器中的url改变了,但是视图始终没有改变.我几乎可以肯定这是因为搜索语句中的?=,但是不知道如何在Python代码中处理它们.

I would like to present a new view after the user submits a search form. I made it as the same way as I do with my other views, but unfortunately this time doesn't happens anything, I can't retrieve the content from the app route. (So this question is not a duplicate of this question, the issue occurs only after submitting the form, it works perfectly in every other situation.) I write something into the form, submit it, then the url changes in the browser, but the view doesn't change anyway. I'm almost sure that it's because the ? and = in the search slug, but don't know how should I deal with them in the Python code.

实际上,当我提交表单时,浏览器会将我重定向到这样的网址:

Actually when I submit the form my browser redirects me to an url like this:

http://domain/.com/?search=content+from+textfield

这就是我尝试从搜索字段中捕获内容并在Flask一侧显示新视图的方式:

And this is how I tried to catch the content from the search field and present a new view on the Flask's side:

@app.route('/?search=<url_content>', methods=['POST'])
def hello_url(url_content): 
return render_template("search-results.html", searchString = url_content])

如果有人可以向我展示正确的方法,我将不胜感激,基本上,我只是想在点击搜索按钮后在hello_url函数内检索<url_content>的值.

I would really appreciate if somebody could show me the right way, basically I just wanna retrieve the value of <url_content> inside the hello_url function after the search button tapped.

这是我的html:

<form>
 <div class="form-group">
    <input type="search" class="form-control text-center input-lg" id="inputSearch" name="search" placeholder="search">
    </div>
     <br>
<div class="text-center"><button type="submit" class="btn btn-primary btn-lg">Search!</button></div>
</form>

推荐答案

您混淆了用<variable>捕获的url参数和通过request.args访问的查询参数.从路由定义中删除查询参数,然后在视图中访问它.

You're confusing url parameters, which are captured with <variable>, with query parameters, which are accessed in request.args. Remove the query parameter from your route definition and access it in the view.

from flask import request

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/search')
def search():
    search = request.args.get('search')  # will be None if form wasn't submitted
    # do something with search
    return render_template('search.html', search=search)

index.html:

<form action="{{ url_for('search') }}">
    <input name="search"/>
    <input type="submit" value="Search"/>
</form>

这篇关于提交搜索表单后,无法通过Flask应用从网址检索变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆