Flask实战第63天:评论布局和功能实现

评论后端逻辑实现

设计评论模型表, 编辑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>
front_pdetail.html

在贴子详情那里绑定帖子id

评论需要用到ueditor编辑器,因此也要引入以下js

{% block head %}
    <script src="{{ url_for('static',filename='ueditor/ueditor.config.js') }}"></script>
    <script src="{{ url_for('static',filename='ueditor/ueditor.all.min.js') }}"></script>
    ...
{% endblock %}

编辑front_pdetail.css,设置样式

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

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

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

.comment-btn-group{
    margin-top: 10px;
    text-align:right;
}

.comment-list-group li{
    overflow: hidden;
    padding: 10px 0;
    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:10px;
}

.comment-content .author-info{
    font-size: 12px;
    color: #8c8c8c;
}

.author-info span{
    margin-right: 10px;
}

.comment-content .comment-txt{
    margin-top: 10px;
}
front_pdetail.css

发表帖子必须要登录才行,为了判断是否登录,我们在front_base.html,设置个登录标签

最后,创建front_pdetail.js并引入

$(function () {
    var ue = UE.getEditor("editor",{
        'serverUrl': '/ueditor/upload/',
        //因为是评论,富文本比编辑器不需要那么多功能,所以这里只列出要用的
        //一个列表代表一行
        "toolbars": [
            [
                'undo', //撤销
                'redo', //重做
                'bold', //加粗
                'italic', //斜体
                'source', //源代码
                'blockquote', //引用
                'selectall', //全选
                'insertcode', //代码语言
                'fontfamily', //字体
                'fontsize', //字号
                'simpleupload', //单图上传
                'emotion' //表情
            ]
        ]
    });
    //把ue设置为全局
    window.ue = ue;
});

$(function () {
    $("#comment-btn").click(function (event) {
        event.preventDefault();
        var loginTag = $("#login-tag").attr("data-is-login");
        if(!loginTag){
            window.location = '/signin/';
        }else{
            var content = window.ue.getContent();
            var post_id = $("#post-content").attr("data-id");
            bbsajax.post({
                'url': '/acomment/',
                'data':{
                    'content': content,
                    'post_id': post_id
                },
                'success': function (data) {
                    if(data['code'] == 200){
                        window.location.reload();
                    }else{
                        xtalert.alertInfo(data['message']);
                    }
                }
            });
        }
    });
});
front_pdetail.js

猜你喜欢

转载自www.cnblogs.com/sellsa/p/9750850.html