Current Location: Home> Latest Articles> Python in Action: Building a CMS Comment Feature with Flask

Python in Action: Building a CMS Comment Feature with Flask

M66 2025-06-15

Introduction

In modern websites, a user comment or message feature plays a crucial role in enhancing interaction and user experience. Whether you're building a corporate site, personal blog, or a full CMS platform, a message module can help gather feedback and promote user engagement. In this guide, we’ll use Python along with Flask and SQLAlchemy to implement a simple and effective CMS message system.

1. Environment Setup

Before we begin, ensure that the following tools and libraries are installed:

  • Python 3.x
  • Flask – A lightweight web framework
  • SQLAlchemy – An ORM tool for easy database management

Install dependencies with:

<span class="fun">pip install flask flask_sqlalchemy</span>

2. Designing the Message Model

The core of the comment system is its database schema. For simplicity, we’ll use SQLite as our local database—ideal for lightweight applications and development environments.

Here’s the data model defined using SQLAlchemy:

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
<p>db = SQLAlchemy()</p>
<p>class Message(db.Model):<br>
id = db.Column(db.Integer, primary_key=True)<br>
content = db.Column(db.String(255), nullable=False)<br>
timestamp = db.Column(db.DateTime, default=datetime.now, nullable=False)<br>

3. Initializing the Database

We initialize the database within our Flask app configuration as follows:

from flask import Flask
<p>app = Flask(<strong>name</strong>)<br>
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///message.db'<br>
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False</p>
<p>db.init_app(app)</p>
<p>with app.app_context():<br>
db.create_all()<br>

4. Displaying User Messages

Next, we implement a page to display the list of messages left by users:

@app.route('/message', methods=['GET'])
def message_list():
    messages = Message.query.all()
    return render_template('message.html', messages=messages)

5. Adding New Messages

Now, let’s create a view that allows users to submit new messages through a form:

@app.route('/message/add', methods=['GET', 'POST'])
def add_message():
    if request.method == 'POST':
        content = request.form.get('content')
        if content:
            message = Message(content=content)
            db.session.add(message)
            db.session.commit()
            flash('Message submitted successfully')
            return redirect(url_for('message_list'))
        else:
            flash('Message content cannot be empty')
    return render_template('add_message.html')

6. Route Registration

Finally, register the routes in your Flask application to ensure both views are accessible:

app.add_url_rule('/message', view_func=message_list)
app.add_url_rule('/message/add', view_func=add_message)

7. Conclusion

In this tutorial, we’ve successfully created a simple comment or message system using Flask and SQLAlchemy. The system allows users to view existing messages and post new ones, making it suitable for lightweight CMS applications.

You can continue to enhance this feature by adding pagination, spam protection, user login systems, and other improvements to suit more advanced use cases.