0
0
Flaskframework~5 mins

HTML forms with POST method in Flask

Choose your learning style9 modes available
Introduction

HTML forms with the POST method let users send data to a server safely. This is useful when you want to submit information like login details or comments.

When a user needs to send sensitive data like passwords.
When submitting a form that changes data on the server, like adding a comment.
When uploading files through a web page.
When you want to avoid showing form data in the URL.
When sending large amounts of data from a form.
Syntax
Flask
<form action="/submit" method="post">
  <input type="text" name="username" />
  <input type="submit" value="Send" />
</form>

The action attribute tells the form where to send the data.

The method="post" means data is sent in the request body, not in the URL.

Examples
A login form sending username and password securely using POST.
Flask
<form action="/login" method="post">
  <label for="user">Username:</label>
  <input type="text" id="user" name="username" />
  <label for="pass">Password:</label>
  <input type="password" id="pass" name="password" />
  <button type="submit">Login</button>
</form>
A comment form where users can write and send text data.
Flask
<form action="/comment" method="post">
  <textarea name="comment" rows="4" cols="50"></textarea>
  <input type="submit" value="Post Comment" />
</form>
Sample Program

This Flask app shows a simple form asking for a name. When the user submits, the server receives the data using POST and replies with a greeting.

Flask
from flask import Flask, request, render_template_string

app = Flask(__name__)

form_html = '''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Simple POST Form</title>
</head>
<body>
  <h1>Enter Your Name</h1>
  <form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="username" required />
    <button type="submit">Send</button>
  </form>
</body>
</html>
'''

@app.route('/')
def index():
    return render_template_string(form_html)

@app.route('/submit', methods=['POST'])
def submit():
    username = request.form.get('username', '')
    return f"Hello, {username}! Your form was submitted successfully."

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use method="post" for sensitive or large data to keep it out of the URL.

Use request.form in Flask to access POSTed form data.

Include required on inputs to help users fill the form correctly.

Summary

HTML forms with POST send data safely in the request body.

Flask uses request.form to read POST data.

Use POST for login, comments, or any data that should not appear in the URL.