• Flask实战第56天:板块管理


    cms布局

    编辑 cms_boards.html

    {% block main_content %}
        <div class="top-box">
            <button class="btn btn-warning" data-toggle="modal" data-target="#banner-dialog">添加新板块</button>
        </div>
    
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>板块名称</th>
                    <th>帖子数量</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    {% endblock %}

    给 “添加轮播图“加上样式”

    {% block head %}
        <style>
            .top-box button{
                float: right;
            }
    
            .top-box{
                overflow: hidden;
                background: #ecedf0;
                padding: 10px;
            }
        </style>
    {% endblock %}

     

    添加新板块后端

    首先添加个表, 因为板块前后端都要用到,编辑apps.models.py

    class BoardModel(db.Model):
        __tablename__ = 'board'
        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        name = db.Column(db.String(20), nullable=False)
        create_time = db.Column(db.DateTime, default=datetime.now)

    同步表到数据库

    >python manage.py db migrate
    python manage.py db upgrade

    添加个表单验证,编辑cms.forms.py

    class AddBoardForm(BaseForm):
        name = StringField(validators=[InputRequired(message='请输入板块名称')])

    编辑cms.views.py

    ...
    from apps.models import BoardModel
    from .forms import AddBoardForm
    
    @bp.route('/aboard/', methods=['POST'])
    @login_required
    @permission_required(CMSPersmission.BOARDER)
    def aboard():
        add_form_board = AddBoardForm(request.form)
        if add_form_board.validate():
            name = add_form_board.name.data
            board = BoardModel(name=name)
            db.session.add(board)
            db.session.commit()
            return xjson.json_success(message='添加板块成功')
        else:
            return xjson.json_param_error(message=add_form_board.get_error())

    添加板块的逻辑写好了,我们顺便把更新板块,删除板块一起写了

    编辑cms.forms.py

    class UpdateBoardForm(AddBoardForm):
        board_id = IntegerField(validators=[InputRequired(message='请输入板块id')])

    编辑cms.views.py

    from .forms import UpdateBoardForm
    
    @bp.route('/uboard/', methods=['POST'])
    @login_required
    @permission_required(CMSPersmission.BOARDER)
    def uboard():
        update_board_form = UpdateBoardForm(request.form)
        if update_board_form.validate():
            board_id = update_board_form.board_id.data
            name = update_board_form.name.data
            if board_id:
                board = BoardModel.query.get(board_id)
                board.name = name
                db.session.commit()
                return xjson.json_success(message='更新成功')
            else:
                return xjson.json_param_error(message='板块不存在')
        else:
            return xjson.json_param_error(message=update_board_form.get_error())
    
    
    @bp.route('/dboard/', methods=['POST'])
    @login_required
    @permission_required(CMSPersmission.BOARDER)
    def dboard():
        board_id = request.form.get('board_id')
        if not board_id:
            return xjson.json_param_error(message='请传入板块id')
        board = BoardModel.query.get(board_id)
        if not board:
            return xjson.json_param_error(message='没有这个板块')
        db.session.delete(board)
        db.session.commit()
        return xjson.json_success(message='删除板块成功')

     传递板块数据到前端页面

    @bp.route('/boards/')
    @login_required
    @permission_required(CMSPersmission.BOARDER)
    def boards():
        all_boards = BoardModel.query.all()
        context = {
            'boards': all_boards
        }
        return render_template('cms/cms_boards.html', **context)

    cms 前端js

    给“添加新板块"按钮加上 id

    <button class="btn btn-warning" data-toggle="modal" data-target="#banner-dialog" id="add-board-btn">添加新板块</button>

    创建static/cms/js/boards.js

    $(function () {
       $('#add-board-btn').click(function (event) {
           event.preventDefault();
           xtalert.alertOneInput({
               'text': '请输入板块名称',
               'placeholder': '板块名称',
               'confirmCallback': function (inputValue) {
                   bbsajax.post({
                       'url': '/cms/aboard/',
                       'data': {
                           'name':inputValue
                       },
                       'success': function (data) {
                           if(data['code'] ==200){
                               window.location.reload();
                           }else{
                               xtalert.alertInfo(data['message'])
                           }
                       }
                   });
               }
           });
       });
    });

    编辑cms_boards.html

    引入boards.js

    {% block head %}
        <script src="{{ url_for('static', filename='cms/js/boards.js')}}"></script>
        ...
    {% endblock %}

    动态展示数据

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>板块名称</th>
                <th>帖子数量</th>
                <th>创建时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for board in boards %}
                <tr>
                    <td>{{ board.name }}</td>
                    <td>暂未实现</td>
                    <td>{{ board.create_time }}</td>
                    <td>
                        <button class="btn btn-default btn-xs edit-board-btn">编辑</button>
                        <button class="btn btn-danger btn-xs delete-board-btn">删除</button>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

     

     编辑板块

    我们先把 板块名称和板块id 绑定到 tr上面,以方便js 获取

    {% for board in boards %}
        <tr data-id="{{ board.id }}" data-name="{{ board.name }}">
            <td>{{ board.name }}</td>
            <td>暂未实现</td>
            <td>{{ board.create_time }}</td>
            <td>
                <button class="btn btn-default btn-xs edit-board-btn">编辑</button>
                <button class="btn btn-danger btn-xs delete-board-btn">删除</button>
            </td>
        </tr>
    {% endfor %}

    编辑banners.js

    $(function () {
       $('.edit-board-btn').click(function () {
           var self = $(this);
           var tr = self.parent().parent();
           var name = tr.attr('data-name');
           var board_id = tr.attr('data-id');
    
           xtalert.alertOneInput({
               'text': '请输入新板块名称',
               'placeholder': name,
               'confirmCallback': function (inputValue) {
                   bbsajax.post({
                       'url': '/cms/uboard/',
                       'data': {
                           'board_id': board_id,
                           'name': inputValue
                       },
                       'success': function (data) {
                           if (data['code'] == 200) {
                               window.location.reload();
                           } else {
                               xtalert.alertInfo(data['message'])
                           }
                       }
                   });
               }
           });
       })
    });

    删除板块

    编辑banner.js

    $(function () {
       $('.delete-board-btn').click(function () {
           var self = $(this);
           var tr = self.parent().parent();
           var board_id = tr.attr('data-id');
    
           bbsajax.post({
               'url': '/cms/dboard/',
               'data': {
                   'board_id': board_id
               },
               'success': function (data) {
                   if (data['code'] == 200) {
                       window.location.reload();
                   } else {
                       xtalert.alertInfo(data['message'])
                   }
               }
           });
       });
    });

     前台页面完成

    视图函数传递板块信息,编辑front_views.py

    @bp.route('/')
    def index():
        banners = BannerModel.query.order_by(BannerModel.priority.desc()).all()
        boards = BoardModel.query.all()
        context = {
            'banners': banners,
            'boards': boards
        }
        return render_template('front/front_index.html', **context)

    编辑front_index.html

    <div class="lg-container">
        <div class="sm-container">
            <div style="padding-bottom: 10px">
                <button class="btn btn-warning btn-block">发布帖子</button>
            </div>
    
            <div class="list-group">
              <a href="#" class="list-group-item active">所有板块</a>
              {% for board in boards %}
                  <a href="#" class="list-group-item ">{{ board.name }}</a>
              {% endfor %}
        </div>
    </div> 

  • 相关阅读:
    我的不足
    对于大数据的一些思考
    对于三层架构的理解
    面试的那些事
    最前端资源汇总——摘自张果博客
    ES6_Promise 对象 阮一锋
    深入理解ES6箭头函数的this以及各类this面试题总结
    函数的扩展——箭头函数this的使用
    ES6学习总结 (二)
    原生js的ajax请求
  • 原文地址:https://www.cnblogs.com/sellsa/p/9694696.html
Copyright © 2020-2023  润新知