【问题标题】:How can I show comments stored in db on my website?如何在我的网站上显示存储在 db 中的评论?
【发布时间】:2022-01-27 20:43:24
【问题描述】:

我想为我的页面创建评论部分,但不是为特定帖子显示 cmets,而是为所有帖子显示 cmets。假设是否有任何用户评论了特定帖子,所以我只希望该帖子的 cmets。我得到的是所有帖子的cmets。让我给你看代码

schema.sql

CREATE TABLE user(
id INTEGER PRIMARY KEY AUTOINCREMENT,
 username TEXT UNIQUE NOT NULL,
 email TEXT UNIQUE NOT NULL,
 password TEXT NOT NULL
);

CREATE TABLE post(
 id INTEGER PRIMARY KEY AUTOINCREMENT,
 author_id INTEGER NOT NULL,
 created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
 title TEXT NOT NULL,
 body TEXT NOT NULL,
 FOREIGN KEY (author_id) REFERENCES user (id)
);

CREATE TABLE comment(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    user_name TEXT UNIQUE NOT NULL,
    comment TEXT NOT NULL,
    FOREIGN KEY (user_name) REFERENCES user (username)
);

blog.py

from flask import(
Blueprint,url_for,render_template,flash,g,redirect,request)
from werkzeug.exceptions import abort

from flaskr.auth import login_required
from flaskr.db import get_db

bp=Blueprint('blog', __name__)

@bp.route('/')
def index():
    db=get_db()
    posts=db.execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' ORDER BY created DESC'
    ).fetchall()
    comments=db.execute(
        'SELECT c.id, comment, created, user_name'
        ' FROM comment c JOIN user u ON c.user_name = u.username'
        ' ORDER BY created ASC'
    ).fetchall()
    return render_template('blog/index.html', posts=posts,comments=comments)

@bp.route('/create', methods=('GET', 'POST'))
@login_required
def create():
    if request.method=='POST':
        title=request.form['title']
        body=request.form['body']
        error=None

        if not title:
            error='Title is required'

        if error is not None:
            flash(error)
        else:
            db=get_db()
            db.execute(
                'INSERT INTO post (title,body,author_id)'
                'VALUES (?,?,?)',
                (title,body,g.user['id']),
            )
            db.commit()
            return redirect(url_for('blog.index'))
    return render_template('blog/create.html')

def get_post(id, check_author=True):
    post=get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (id,),
    ).fetchone()

    if post is None:
        abort(404, f"Post id {id} doesn't exist.")

    if check_author and post['author_id'] != g.user['id']:
        abort(403)

    return post

@bp.route('/<int:id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
    post=get_post(id)
    if request.method=='POST':
        title=request.form['title']
        body=request.form['body']
        error=None

        if not title:
            error='Title is required'

        if error is not None:
            flash(error)
        else:
            db=get_db()
            db.execute(
                'UPDATE post SET title = ?, body = ?'
                ' WHERE id=?',
                (title,body,id),
            )
            db.commit()
            return redirect(url_for('blog.index'))
    return render_template('blog/update.html', post=post)

@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(id):
    get_post(id)
    db=get_db()
    db.execute('DELETE FROM post WHERE id=?',(id,))
    db.commit()
    return redirect(url_for('blog.index'))

@bp.route('/<int:id>/comment', methods=('GET','POST'))
@login_required
def comment(id):
    post=get_post(id)
    if request.method=='POST':
        comment=request.form['comment']
        error=None

        if not comment:
            error='Please type comment and try again.'

        if error is not None:
            flash(error)
        else:
            db=get_db()
            db.execute(
                'INSERT INTO comment (comment,user_name)'
                'VALUES (?,?)',
                (comment,g.user['username'],),
            )
            db.commit()
            return redirect(url_for('blog.index'))
    return render_template('blog/comment.html')

index.html

{% extends 'base.html' %}

{% block header %}
    <h1>{% block title %}Posts{% endblock %}</h1>
    {% if g.user %}
        <a class="action" href="{{url_for('blog.create')}}">New</a>
    {% endif %}
{% endblock %}

{% block content %}
    {% for post in posts %}
        <article class="post">
            <header>
                <div>
                    <h1>{{ post['title'] }}</h1>
                    <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
                </div>
                {% if g.user['id']==post['author_id'] %}
                    <a class="action" href="{{url_for('blog.update', id=post['id'])}}">Edit</a>
                {% endif %}
                {% if g.user %}
                    <a class="action" href="{{url_for('blog.comment', id=post['id'])}}">Comment</a>
                {% endif %}
            </header>
            <p class="body">{{ post['body'] }}</p>
            {% for comment in comments %}
                <ul class="comments">
                    <li><span>{{comment['user_name']}}</span> {{comment['comment']}}</li>
                </ul>  
            {% endfor %}
        </article>
        {% if not loop.last %}
            <hr>
        {% endif %}
    {% endfor %}
{% endblock %}

【问题讨论】:

    标签: sqlite flask jinja2


    【解决方案1】:

    cmets 表结构似乎不正确。

    评论表应该有 post_id 作为外键 id,这将表示该特定评论属于列中提到该 id 的特定帖子。

    你需要在这里做三件事:

    1. 更改 cmets 表并在此处添加 post_id 作为外键。
    CREATE TABLE comment(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        user_name TEXT UNIQUE NOT NULL,
        comment TEXT NOT NULL,
        FOREIGN KEY (user_name) REFERENCES user (username)
        FOREIGN KEY (post_id) REFERENCES post (post_id)
    );
    
    1. 每当用户 cmets 发送该特定帖子的 post_id 并将 post_id 填充到 cmets 表中。

    2. 更改您的检索查询,您可以在其中获取特定于帖子和用户的 cmets。

    如果您这样做正确,那么这应该很容易完成。 在这里看不到任何拦截器。

    【讨论】:

    • 谢谢大哥!!它真的很有帮助:)
    • 欢迎您!如果解决方案能够解决您的问题,请您接受。它会帮助我。
    • 哦抱歉我忘记接受了!!完成??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多