简体   繁体   中英

How to add a comment feature Python Flask MySQL?

Before we start, I'm a complete beginner. This is the best I can do at the moment. I have no idea where to start with adding a comment feature to my app. This is what I have for now - it's not much, but it works. Here's my Python code:

@app.route('/forum')
def forum():
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("SELECT * FROM posts_announcements ORDER BY id DESC LIMIT 1")
    last_post = cursor.fetchone()
    if 'loggedin' in session:
        return render_template('forum.html', last_post=last_post, username=session['username'])
    return render_template('forum.html', last_post=last_post)

@app.route('/forum/announcements/posts/<id>', methods=['GET', 'POST'])
def post(id):
    if 'loggedin' in session:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cursor.execute("SELECT * FROM posts_announcements WHERE id = %s", [id])
        post = cursor.fetchone()
        return render_template('post.html', post=post, username=session['username'])
    else:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cursor.execute("SELECT * FROM posts_announcements WHERE id = %s", [id])
        post = cursor.fetchone()
        return render_template('post.html', post=post)

@app.route('/forum/announcements/desc/')
def announcements_desc():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    limit = 20
    offset = page*limit - limit
    if 'loggedin' in session:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute("SELECT * FROM posts_announcements")
        result = cursor.fetchall()
        total = len(result)
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cur.execute("SELECT * FROM posts_announcements ORDER BY UNIX_TIMESTAMP(date_of_creation) DESC LIMIT %s OFFSET %s;", (limit, offset))
        posts_announcements = cur.fetchall()
        cur.close()
        pagination = Pagination(page=page, per_page=limit, total=total, record_name='posts_announcements')
        return render_template('announcements_desc.html', pagination=pagination, posts_announcements=posts_announcements, username=session['username'])
    else:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cursor.execute("SELECT * FROM posts_announcements ORDER BY UNIX_TIMESTAMP(date_of_creation) DESC")
        posts_announcements = cursor.fetchall()
        return render_template('announcements_asc.html', posts_announcements=posts_announcements)

@app.route('/forum/announcements/asc')
def announcements_asc():
    if 'loggedin' in session:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cursor.execute("SELECT * FROM posts_announcements ORDER BY UNIX_TIMESTAMP(date_of_creation) ASC")
        posts_announcements = cursor.fetchall()
        return render_template('announcements_asc.html',posts_announcements=posts_announcements, korisničkoime=session['korisničkoime'])
    else:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cursor.execute("SELECT * FROM posts_announcements ORDER BY UNIX_TIMESTAMP(date_of_creation) ASC")
        posts_announcements = cursor.fetchall()
        return render_template('announcements_asc.html', posts_announcements=posts_announcements)

So for now, I have created posts and I can access the last post from the forum page. I also added an option to order my posts in the descending and ascending order on click. But that was mainly MySQL code. Here's my HTML, this is my forum.html

<div class="forums-right-forum">
    <div><a class="reveal_title" href="/forum/announcements/posts/{{ last_post.id }}">{{ last_post.title }}</a></div>
    <span><a href="#">{{ last_post.author }}</a></span>
    <p>{{ last_post.date_of_creation }}</p>
</div>

This is my post.html

<div class="divmid-box-post">
    <div class="date"><p>{{ post.date_of_creation }}</p></div>                  
    <div class="user">
        <a class="post_author" href="#">{{ post.author }}</a>
    </div>
    <div class="post" id="post">
        <div class="message">{{ post.message | safe }}</div>
    </div>
</div>

Here's the forum page which redirects to different posts:

<div>
    <ul>
        <a class="post-title" href="/forum/announcements/posts/{{ post.id }}">{{ post.title }}</a>
        <br>
        Author:<a class="author" href="#"> {{ post.author }}</a><p>{{ post.date_of_creation }}</p>
    </ul>
</div>

This is all working as expected, but now I would like to add a comment feature to my posts and I don't know how to play with classes. I only have a main.py file and everything I have is inside there. I just want someone to point me in the right direction because every post I went through was with SQLAlchemy or other different databases. I believe the solution could be very simple, but I just don't get it and as I said before, I'm a complete beginner. Thanks in advance!

EDIT: I tried this, but it's not working as expected:

@app.route('/forum/announcements/posts/<id>', methods=['GET', 'POST'])
def post(id):
    if 'loggedin' in session:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result = cursor.execute("SELECT * FROM posts_announcements WHERE id = %s", [id])
        post = cursor.fetchone()
        cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        result1 = cur.execute("SELECT * FROM comments_announcements")
        comment = cur.fetchall()
        if request.method == 'POST' and 'comment' in request.form:
            comment1 = bbcode.render_html(request.form['comment'])
            author = session['username']
            cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
            cursor.execute("INSERT INTO comments_announcements(message, author) VALUES (%s, %s)", (comment1, author))
            mysql.connection.commit()
            return render_template('post.html', post=post, comment=comment, username=session['username'])
        return render_template('post.html', post=post, comment=comment, username=session['username'])
    return render_template('post.html', post=post, comment=comment)

I get the data to the database, but I can't seem to show it in my html via {{ comment.title }} {{ comment.author }} or {{ comment.message }}

I did this, but it's not working:

{% for comment in comments_announcements %}
            <div class="divmid-box-comment">
                <div class="date_of_creation"><p>{{ comment.date_of_creation }}</p></div>                   
                <div class="author">
                    <a class="post_author" href="#">{{ comment.author }}</a>
                </div>
                <div class="post" id="post">
                    <div class="comment_message">{{ comment.message | safe }}</div>
                </div>
            </div>
{% endfor %}

In comment you have many comments (and maybe you should use name with s at the end)
and inside template you should use loop to display all comments.

{{ for c in comment }} 
    {{ c.title }} 
    {{ c.author }}
    {{ c.message }}
{{ endfor }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM