提问者:小点点

Python:基于表单提交发送到某个URL


我试图创建一个搜索栏,它将根据用户在“结果”页面上键入的查询将用户发送到某些URL,例如“/results?。 我已经成功地制作了结果页面URL为/results的版本,但这并不是我真正想要的。

以下是HTML脚本:

<!--index.html-->
<form action="{{ url_for('search') }}" method="post">
    <input type="text" id="search" name="form_search" placeholder="Type here">
</form>

下面是Python脚本,我将结果定向到/resultsURL:

#app.py
@app.route("/")
def index():
    return render_template("index.html")

...

# I want to direct this to "/results?<form_search>"
# I think I need to put the line below somewhere but I'm not sure where
# form_search = request.form.get("form_search")

@app.route("/results", methods=["POST"]) # Want to change it to "/results?<form_search>"
def search(form_search):
    ...
    return render_template("results.html", form_search=form_search, results=results)

有人能帮忙吗?


共1个答案

匿名用户

我几乎没有使用过flask,但是如果你想要拥有动态URL,你需要将其添加到@app.route decorator中,例如:如果我想要一个用户名被发布到URL中,这就是它的样子:

@app.route("/<username>")          # str,int,uuid,float,path also works
def user_name(username=None, post_id=None):     
    return render_template("index.html", name=username)

当谈到从表单中获取数据时,我可以向您展示一个类似于我在django中所做的示例(我有一段时间没有使用flask,因此您可能需要自己进行一些实验)--这是一个在类中创建的方法:

    def get_queryset(self):
      query = self.request.GET.get(
        "searchrecipe")  # searchrecipe is the name of our input form, means: the value we enter in the form -> This might also work for FLASK, get the data with request.get and FORM NAME
      object_list = Recipe.objects.filter(name__icontains=query) #This filters the data in my database (aftger name) so not relevant for you
      return object_list