BBS Forum (30)

BBS Forum (30)

30. The function of displaying comments and adding comments is complete

(1) 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(50), db.ForeignKey('front_user.id'), nullable=False)

    post=db.relationship('PostModel',backref='comments')
    author=db.relationship('FrontUser',backref='comments')

生成到数据库

python manage.py migrate

python manage.py upgrade

(2)front/forms.py

class AddCommentForm(BaseForm):
    content=StringField(validators=[InputRequired(message='请输入评论内容')])
    post_id=IntegerField(validators=[InputRequired(message='请输入评论内容')])

(3)front/views.py

@bp.route('/acomment/',methods=['POST'])
@login_requried
def add_comment():
    form=AddCommentForm(request.form)
    if form.validate():
        content=form.content.data
        post_id=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 restful.success()
        else:
            return restful.params_error(message='There is no such post')
    else:
        return restful.params_error(form.get_error())

(4) front/front_base.html

<span id="login-tag" data-is-login="1"></span>

(5) front/front_pdetail.html

{% extends'front/front_base.html' %}
{% from'common/_macros.html' import static %}

{% block title %}
    {{ post.title }}
{% endblock %}

{% block head %}
    <script src="{{ static('ueditor/ueditor.config.js') }}"></script>
    <script src="{{ static('ueditor/ueditor.all.min.js') }}"></script>
    <script src="{{ static('front/js/front_pdetail.js') }}"></script>
    <link rel="stylesheet" href="{{ static('front/css/front_pdetail.css') }}">
{% endblock %}

{% block body %}
    <div class="lg-container">
        <div class="post-container">
            <h2>{{ post.title }}</h2>
            <p class="post-info-group">
                <span>Post time: {{ post.create_time }}</span>
                <Span> OF: {{post.author.username}} </span>
                <span>Board: {{ post.board.name }}</span>
                <span>Read count: {{ post.read_count }}</span>
                <span>Number of comments: 0</span>
            </p>
            <article class="post-content" id="post-content" data-id="{{ post.id }}">
                {{ post.content|safe }}
            </article>
        </div>

      <div class="comment-group">
        <h4>Comment list:</h4>
        <ul class="comment-list-group">
            {% for comment in post.comments %}
                <li>
                <div class="avatar-group">
                    <img src="{{ comment.author.avatar or static('common/images/logo.jpg') }}" 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>Add comment</h3>
        <script id="editor" style="height:100px;" type="text/plain"></script>
        <div class="add_comment_btn">

            <button class="btn btn-primary" id='comment-btn'>Post a comment</button>
        </div>

    </div>

    </div>
    <div class="sm-container"></div>
{% endblock %}

(6) front/css/front_pdetail.css

.comment-group{
    border:1px solid #e8e8e8;
    margin-top: 20px;
    padding: 10px;
}
.add-comment-group{

    border:1px solid #e8e8e8;
    margin-top: 20px;
}
.add_comment_btn{
    text-align: right;
    margin: 10px;

}
.add-comment-group h3{
    margin: 10px;
}

.comment-list-group li{
    overflow:hidden;
    border-bottom:1px solid #e8e8e8;

}
.avatar-group{
    float:left;
}
.avatar-group img{
    width: 50px;
    height: 50px;
    border-radius: 50%;
}
.comment-content{
    float: left;
    margin-left: 20px;
}
.comment-content .author-info{
    font-size: 12px;
    color:#8c8c8c;
}
.author-info span{
    margin-right:10px;
}
.comment-content .comment-txt{
    margin-top: 10px;
}

(7) front/front_pdetail.js

$(function(){

    var ue=UE.getEditor('editor',{
        'serverUrl':'/ueditor/upload/',
        "toolbars": [
            [
                'undo',//undo
                'redo',//redo
                'bold',//bold
                'italic',//italic
                'blockquote',//quote
                'selectall',//select all
                'fontfamily',//font
                'fontsize',//font size
                'simpleupload',//Single image upload
                'emotion'//Emotion
            ]
        ]
    });
    window.ue=ue;
});

$(function(){
   $('#comment-btn').on('click',function(event){
       event.preventDefault();
       var login_tag=$('#login-tag').attr('data-is-login');
       if (! login_tag){
           win.loc='/signin/'
       }else{
           var content=window.ue.getContent();
           var post_id=$('#post-content').attr('data-id');
           zlajax.post({
              'url':'/acomment/',
               'data':{
                  'content':content,
                   'post_id':post_id
               },
               'success':function(data){
                  if(data['code']==200){
                      zlalert.alertSuccessToast(msg='Comment published successfully');
                      win.loc.reload();
                  }else{
                        zlalert.alertInfo(data['message']);
                  }
               }
           });
       }

   });
});
Reference: https://cloud.tencent.com/developer/article/1390478 BBS Forum (30)-Cloud + Community-Tencent Cloud