Passing values from HTML form to Python Flask.

huangapple go评论65阅读模式
英文:

Passing values from HTML form to Python Flask

问题

以下是您要翻译的内容:

"I've already seen this question, but my code still doesn't work. I have 3 files (main.py and add.html are important here).

The user enters book name, author and rating (in '/add'), and the given values should be passed to main.py and printed out. But it gives me a 400 error, even though I gave the needed values in add.html and in main.py.

Can someone help me find what's wrong?

Thanks."

请注意,这是您提供的英文文本,已经没有代码部分了。如果您需要对特定部分进行翻译,请提供相应的文本。

英文:

I've already seen this question, but my code still doesn't work. I have 3 files (main.py and add.html are important here).

The user enters book name, author and rating (in '/add'), and the given values should be passed to main.py and printed out. But it gives me an 400 error, even thou I gave the needed values in add.html and in main.py.

Can someone help me find what's wrong?

Thanks.

main.py

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

all_books = []


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


@app.route('/add', methods=['GET', 'POST'])
def add():
  book_name = request.form['bookName']
  book_author = request.form['book-author']
  book_rating = request.form['book-rating']
  return f"<h1>Name: {book_name}, Author: {book_author}, Rating: {book_rating}</h1>"


if __name__ == "__main__":
  app.run(host='0.0.0.0', debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Library</title>
</head>
<body>
<h1>My Library</h1>
    <ul>
        <li></li>
    </ul>
    
<a href="{{ url_for('add') }}">Add New Book</a>
</body>
</html>

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Book</title>
</head>
<body>
  <form action="/add" method="post">
    <label>Book Name</label>
    <input type="text" id="bookName" name="book-name">
    <label>Book Author</label>
    <input type="text" id="book-author" name="book-author">
    <label>Rating</label>
    <input type="text" id="book-rating" name="book-rating">
    <button type="submit">Add Book</button>
  </form>
</body>
</html>

答案1

得分: 1

问题在于你尝试在/add路由上执行两个任务,首先尝试显示add.html页面,其次处理该页面上的表单。你需要通过创建一个单独的路由来分离这两个任务。

代码:

@app.route('/added', methods=['GET', 'POST'])
def added():
  book_name = request.form['book-name']
  book_author = request.form['book-author']
  book_rating = request.form['book-rating']
  return f"<h1>Name: {book_name}, Author: {book_author}, Rating: {book_rating}</h1>"

现在在add.html表单中调用/added

<form action="/added" method="POST">
英文:

The problem is that you try to use the /add route for two things, first trying to display the add.html page and second processing the form on that page. You need to separate these two by creating a separate route for displaying the page.

Code:

@app.route(&#39;/add&#39;)
def add():
  return render_template(&#39;add.html&#39;)

@app.route(&#39;/added&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def added():
  book_name = request.form[&#39;book-name&#39;]
  book_author = request.form[&#39;book-author&#39;]
  book_rating = request.form[&#39;book-rating&#39;]
  return f&quot;&lt;h1&gt;Name: {book_name}, Author: {book_author}, Rating: {book_rating}&lt;/h1&gt;&quot;

Now call /added from the form in add.html:

&lt;form action=&quot;/added&quot; method=&quot;POST&quot;&gt;

答案2

得分: 0

我发现了一个解决方案,而不是像@Marijn那样添加新路由。我在index.html中将路由改为动态。以下是main.py和add.html的代码:

main.py

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

all_books = []


@app.route('/')
def home():
    return render_template("index.html", books=all_books)


@app.route("/add", methods=["GET", "POST"])
def add():
    if request.method == "POST":
        new_book = {
            "title": request.form["title"],
            "author": request.form["author"],
            "rating": request.form["rating"]
        }
        all_books.append(new_book)
    return render_template("add.html")


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Book</title>
</head>
<body>
    <form action="{{ url_for('add') }}" method="POST">
        <label>Book Name</label>
        <input name="title" type="text">
        <label>Book Author</label>
        <input name="author" type="text">
        <label>Rating</label>
        <input name="rating" type="text">
        <button type="submit">Add Book</button>
    </form>
</body>
</html>
英文:

So I found out a solution to the problem without adding a new route as @Marijn did. I changed the route in index.html to be dynamic. Here is the code for main.py and add.html:

I also changed the part where instead of printing it out it adds it as a dictionary to a list (this doesn't have anything to do with the question so don't mind that part).

main.py

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

all_books = []


@app.route(&#39;/&#39;)
def home():
    return render_template(&quot;index.html&quot;, books=all_books)


@app.route(&quot;/add&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
def add():
    if request.method == &quot;POST&quot;:
        new_book = {
            &quot;title&quot;: request.form[&quot;title&quot;],
            &quot;author&quot;: request.form[&quot;author&quot;],
            &quot;rating&quot;: request.form[&quot;rating&quot;]
        }
        all_books.append(new_book)
    return render_template(&quot;add.html&quot;)


if __name__ == &quot;__main__&quot;:
    app.run(host=&#39;0.0.0.0&#39;, debug=True)

add.html

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;Add Book&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form action=&quot;{{ url_for(&#39;add&#39;) }}&quot; method=&quot;POST&quot;&gt;
        &lt;label&gt;Book Name&lt;/label&gt;
        &lt;input name=&quot;title&quot; type=&quot;text&quot;&gt;
        &lt;label&gt;Book Author&lt;/label&gt;
        &lt;input name=&quot;author&quot; type=&quot;text&quot;&gt;
        &lt;label&gt;Rating&lt;/label&gt;
        &lt;input name=&quot;rating&quot; type=&quot;text&quot;&gt;
        &lt;button type=&quot;submit&quot;&gt;Add Book&lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

huangapple
  • 本文由 发表于 2023年4月20日 02:11:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定