我想為我的頁面創建評論部分,但不是顯示特定帖子的評論,而是顯示所有帖子的評論。假設是否有任何用戶對特定帖子發表了評論,那么我只想要該帖子的評論。我得到的是所有帖子的評論。讓我給你看代碼
模式.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)
);
博客.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')
索引.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 %}
uj5u.com熱心網友回復:
評論表結構似乎不正確。
評論表應該有 post_id 作為外鍵 id,這將表示此特定評論屬于列中提及該 id 的特定帖子。
你需要在這里做三件事:
- 更改評論表并在那里添加 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)
);
每當用戶評論時,發送該特定帖子的 post_id 并在評論表中填充 post_id。
更改檢索查詢,在其中獲取特定于帖子和用戶的評論。
如果你這樣做正確,那么這應該很容易做到。在這里看不到任何攔截器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400418.html
上一篇:Python-在回傳陳述句上縮進
