评论后端逻辑实现
设计评论模型表, 编辑apps.models.py
class CommentModel(db.Model): __tablename__ = 'comment' id = db.Column(db.Integer,primary_key=True,autoincrement=True) content = db.Column(db.Text,nullable=False) create_time = db.Column(db.DateTime,default=datetime.now) post_id = db.Column(db.Integer,db.ForeignKey("post.id")) author_id = db.Column(db.String(100), db.ForeignKey("front_user.id"), nullable=False) post = db.relationship("PostModel",backref='comments') author = db.relationship("FrontUser",backref='comments')
同步表到数据库
python manage.py db migrate
python manage.py db upgrade
后端需要对评论进行表单验证,编辑front.forms.py
class AddCommentForm(BaseForm): content = StringField(validators=[InputRequired(message='请输入评论内容!')]) post_id = IntegerField(validators=[InputRequired(message='请输入帖子id!')])
写视图函数,编辑front.views.py
from .forms import AddCommentForm from apps.models import CommentModel ... @bp.route('/acomment/',methods=['POST']) @login_required def add_comment(): add_comment_form = AddCommentForm(request.form) if add_comment_form.validate(): content = add_comment_form.content.data post_id = add_comment_form.post_id.data post = PostModel.query.get(post_id) if post: comment = CommentModel(content=content) comment.post = post comment.author = g.front_user db.session.add(comment) db.session.commit() return xjson.json_success() else: return xjson.json_param_error('没有这篇帖子!') else: return xjson.json_param_error(add_comment_form.get_error())
评论前端布局
<div class="lg-container"> ... <div class="comment-group"> <h3>评论列表</h3> <ul class="comment-list-group"> {% for comment in post.comments %} <li> <div class="avatar-group"> <img src="{{ comment.author.avatar or url_for('static', filename='common/images/logo.png') }}" alt=""> </div> <div class="comment-content"> <p class="author-info"> <span>{{ comment.author.username }}</span> <span>{{ comment.create_time }}</span> </p> <p class="comment-txt"> {{ comment.content|safe }} </p> </div> </li> {% endfor %} </ul> </div> <div class="add-comment-group"> <h3>发表评论</h3> <script id="editor" type="text/plain" style="height:100px;"></script> <div class="comment-btn-group"> <button class="btn btn-primary" id="comment-btn">发表评论</button> </div> </div> </div>