How to Save Data Into Database from Web Form Using Python

 Here’s a comprehensive Python script to collect data from a form (Form1) and store it into a test database using a relational database management system like SQLite. The example below uses Flask for the web framework to handle the form submission and SQLAlchemy for database interaction.

Steps Covered

  1. Set up Flask app to handle HTTP requests.
  2. Create a database with SQLAlchemy.
  3. Define the form and database model.
  4. Store submitted data into the database.

PYthon Code to Handle HTTP Request

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

app = Flask(__name__)

# Configure the SQLite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Define the database model
class FormData(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(120), nullable=False)
    message = db.Column(db.Text, nullable=True)

    def __repr__(self):
        return f"<FormData {self.name}>"

# Initialize the database
with app.app_context():
    db.create_all()

# Route for the form
@app.route('/', methods=['GET', 'POST'])
def form1():
    if request.method == 'POST':
        # Collect form data
        name = request.form['name']
        email = request.form['email']
        message = request.form.get('message', '')

        # Validate required fields
        if not name or not email:
            return "Name and Email are required!", 400

        # Save to database
        form_data = FormData(name=name, email=email, message=message)
        db.session.add(form_data)
        db.session.commit()

        return redirect(url_for('thank_you'))

    return render_template('form.html')

# Thank you page
@app.route('/thank-you')
def thank_you():
    return "<h1>Thank you for your submission!</h1>"

# View stored data (optional)
@app.route('/view-data')
def view_data():
    all_data = FormData.query.all()
    return render_template('view_data.html', data=all_data)

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

Create a file named form.html in the templates directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form</title>
</head>
<body>
    <h1>Submit Your Information</h1>
    <form method="POST" action="/">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>

        <label for="message">Message:</label>
        <textarea id="message" name="message"></textarea>
        <br><br>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

Create a file named view_data.html in the templates directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Data</title>
</head>
<body>
    <h1>Submitted Data</h1>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Message</th>
            </tr>
        </thead>
        <tbody>
            {% for item in data %}
            <tr>
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.email }}</td>
                <td>{{ item.message }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

  1. Install All Packages i.e pip install flask flask-sqlalchemy.
  2. Run the Application python app.py
  3. Open your browser at http://127.0.0.1:5000/.

Admin

A Software Engineer, Social Media Marketing Expert, writer,

Post a Comment

Previous Post Next Post