Flask 构建微电影视频网站(4.1)

后台管理

实现后台管理系统使用flask sqlalchemy结合mysql数据库进行增删改查操作、分页的使用、路由装饰器定义、模板中变量调用、登录会话机制、上传文件、flask wtforms表单使用。

管理员登录

models进行重构,将数据库的配置信息放在app/__init__.py文件中

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:123456@127.0.0.1:3306/movie'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY'] = 'cb34xxxxxxxxxxxxxxxxxxbae30d90f6'

db = SQLAlchemy(app)

models文件中直接引入db

from app import db

定义登陆表单字段
app/admin/forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, ValidationError

from app.models import Admin


class LoginForm(FlaskForm):
    '''
    管理员登陆表单
    '''
    account = StringField(
        label='账号',
        validators=[
            DataRequired("请输入账号!")
        ],
        description="账号",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入账号!",
            "required": "required"
        }
    )
    pwd = PasswordField(
        label='密码',
        validators=[
            DataRequired("请输入密码!")
        ],
        description="密码",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入密码!",
            "required": "required"
        }
    )
    submit = SubmitField(
        '登录',
        render_kw={
            "class": "btn btn-primary btn-block btn-flat",
        }
    )

    def validate_account(self, field):
        account = field.data
        admin = Admin.query.filter_by(name=account).count()
        if admin == 0:
            raise ValidationError("账号不存在!")

render_kw里的样式是前端代码中的

编写试图函数

# 装饰器用来进行访问控制
def admin_login_req(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if session.get('admin', None) is None:
            return redirect(url_for('admin.login', next=request.url))
        return func(*args, **kwargs)
    return decorated_function
@admin.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        data = form.data
        admin = Admin.query.filter_by(name=data['account']).first()
        if not admin.check_pwd(data['pwd']):
            flash("账号或密码错误! ")
            return redirect(url_for('admin.login'))
        session['admin'] = data['account']
        return redirect((request.args.get('next') or url_for('admin.index')))
    return render_template('admin/login.html', form=form)


@admin.route('/logout/')
@admin_login_req
def logout():
    session.clear()
    return redirect(url_for('admin.login'))

在每一个需要进行登陆才能操作的视图函数中加入装饰器,像logout视图一样
Admin模型中添加密码校验函数

    def check_pwd(self, pwd):
        from werkzeug.security import check_password_hash
        return check_password_hash(self.pwd, pwd)

修改模板app/templates/admin/login.html

    <div class="login-box-body">
        {% for message in get_flashed_messages() %}
            <p class="login-box-msg" style="color: red">{{ message }}</p>
        {% endfor %}

        <form action="" method="post" id="form-data">
            <div class="form-group has-feedback">
                {{ form.account }}
                <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
                {% for err in form.account.errors %}
                    <div class="col-md-12" id="input_user" style="color: red">{{ err }}</div>
                {% endfor %}

            </div>
            <div class="form-group has-feedback">
                {{ form.pwd }}
                <span class="glyphicon glyphicon-lock form-control-feedback"></span>
                {% for err in form.pwd.errors %}
                    <div class="col-md-12" id="input_pwd" style="color: red">{{ err }}</div>
                {% endfor %}
            </div>
            <div class="row">
                <div class="col-xs-8">
                </div>
                <div class="col-xs-4">
                    {{ form.submit }}
                    {{ form.csrf_token }}
                </div>
            </div>
        </form>
    </div>

标签管理

创建一个表单form
app/admin/forms.py

class TagForm(FlaskForm):
    name = StringField(
        label='名称',
        validators=[
            DataRequired("请输入标签!")
        ],
        description="名称",
        render_kw={
            "class": "form-control",
            "id": "input_name",
            "placeholder": "请输入标签名称!"
        }
    )
    submit = SubmitField(
        '编辑',
        render_kw={
            "class": "btn btn-primary"
        }
    )
添加标签

视图函数

@admin.route('/tag/add/', methods=['GET', 'POST'])
@admin_login_req
def tag_add():
    form = TagForm()
    if form.validate_on_submit():
        data = form.data
        tag = Tag.query.filter_by(name=data['name']).count()
        if tag == 1:
            flash("标签已存在!", 'error')
            return redirect(url_for('admin.tag_add'))
        tag = Tag(
            name=data['name']
        )
        db.session.add(tag)
        db.session.commit()
        flash("标签添加成功!", 'info')
        return redirect(url_for('admin.tag_add'))
    return render_template('admin/tag_add.html', form=form)

修改前端代码

<form role="form" method="post">
    <div class="box-body">
        {% for message in get_flashed_messages(category_filter=['info']) %}
            <div class="alert alert-success alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
                </button>
                <h4><i class="icon fa fa-check"></i> 操作成功!</h4>
                {{ message }}
            </div>
        {% endfor %}
        {% for message in get_flashed_messages(category_filter=['error']) %}
            <div class="alert alert-danger alert-dismissible">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
                </button>
                <h4><i class="icon fa fa-ban"></i> 操作失败!</h4>
                {{ message }}
            </div>
        {% endfor %}


        <div class="form-group">
            <label for="input_name">{{ form.name.label }}</label>
            {{ form.name }}
            {% for err in form.name.errors %}
                <div class="col-md-12" id="input_user" style="color: red">{{ err }}</div>
            {% endfor %}
        </div>
    </div>
    <div class="box-footer">
        {{ form.submit }}
        {{ form.csrf_token }}
    </div>
</form>
标签列表

视图函数

@admin.route('/tag/list/<int:page>/')
@admin_login_req
def tag_list(page=1):
    if page <= 0:
        page = 1
    page_data = Tag.query.order_by(
        Tag.addtime.desc()
    ).paginate(page=page, per_page=10)
    return render_template('admin/tag_list.html', page_data=page_data)

修改前端代码

<div class="box-body table-responsive no-padding">
    {% for message in get_flashed_messages(category_filter=['info']) %}
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
            </button>
            <h4><i class="icon fa fa-check"></i> 操作成功!</h4>
            {{ message }}
        </div>
    {% endfor %}
    <table class="table table-hover">
        <tbody>
        <tr>
            <th>编号</th>
            <th>名称</th>
            <th>添加时间</th>
            <th>操作事项</th>
        </tr>
        {% for tag in page_data.items %}
            <tr>
                <td>{{ tag.id }}</td>
                <td>{{ tag.name }}</td>
                <td>{{ tag.addtime }}</td>
                <td>
                    <a href="{{ url_for('admin.tag_edit', id=tag.id) }}" class="label label-success">编辑</a>
                    &nbsp;
                    <a href="{{ url_for('admin.tag_del', id=tag.id) }}" class="label label-danger">删除</a>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

当标签较多时,需要对标签进行分页
分页http://www.pythondoc.com/flask-sqlalchemy/api.html?highlight=paginate#id4

新建一个分页的macro
app/templates/ui/admin_page.html

{% macro pagination(data, url) -%}
    {% if data %}
        <ul class="pagination pagination-sm no-margin pull-right">
            <li><a href="{{ url_for(url, page=1) }}">首页</a></li>

            {% if data.has_prev %}
                <li><a href="{{ url_for(url, page=data.prev_num) }}">上一页</a></li>
            {% else %}
                <li class="disabled"><a href="#">上一页</a></li>
            {% endif %}

            {% for v in data.iter_pages() %}
                {% if v == data.page %}
                    <li class="active"><a href="#">{{ v }}</a></li>
                {% else %}
                    <li><a href="{{ url_for(url, page=v) }}">{{ v }}</a></li>
                {% endif %}
            {% endfor %}

            {% if data.has_next %}
                <li><a href="{{ url_for(url, page=data.next_num) }}">下一页</a></li>
            {% else %}
                <li class="disabled"><a href="#">下一页</a></li>
            {% endif %}

            <li><a href="{{ url_for(url, page=data.pages) }}">尾页</a></li>
        </ul>

    {% endif %}
{%- endmacro %}

在标签列表中使用这个macro

{% extends 'admin/admin.html' %}
{% from 'ui/admin_page.html' import pagination %}

...

<div class="box-footer clearfix">
    {{ pagination(page_data, 'admin.tag_list') }}
</div>
删除标签

视图函数

@admin.route('/tag/del/<int:id>/')
@admin_login_req
def tag_del(id=None):
    tag = Tag.query.filter_by(id=id).first_or_404()
    db.session.delete(tag)
    db.session.commit()
    flash('删除标签成功!', 'info')
    return redirect(url_for('admin.tag_list', page=1))

修改标签列表中删除按钮的a标签

<a href="{{ url_for('admin.tag_del', id=tag.id) }}" class="label label-danger">删除</a>
修改标签

视图函数

@admin.route('/tag/edit/<int:id>/', methods=['GET', 'POST'])
@admin_login_req
def tag_edit(id=None):
    form = TagForm()
    tag = Tag.query.get_or_404(id)
    if form.validate_on_submit():
        data = form.data
        tag_count = Tag.query.filter_by(name=data['name']).count()
        if tag.name != data['name'] and tag_count == 1:
            flash("标签已存在!", 'error')
            return redirect(url_for('admin.tag_edit', id=id))
        tag.name=data['name']
        db.session.add(tag)
        db.session.commit()
        flash("标签修改成功!", 'info')
        return redirect(url_for('admin.tag_list', page=1))
    return render_template('admin/tag_edit.html', form=form, tag=tag)

新建app/templates/admin/tag_edit.html,用来进行标签的修改
代码和添加标签中的几乎一致,只是需要显示标签的名字

<div class="form-group">
    <label for="input_name">{{ form.name.label }}</label>
    {{ form.name(value=tag.name) }}
    {% for err in form.name.errors %}
        <div class="col-md-12" id="input_user" style="color: red">{{ err }}</div>
    {% endfor %}
</div>

电影管理

新建电影表单
app/admin/forms.py

class MovieForm(FlaskForm):
    title = StringField(
        label='片名',
        validators=[
            DataRequired("请输入片名!")
        ],
        description="片名",
        render_kw={
            "class": "form-control",
            "id": "input_title",
            "placeholder": "请输入片名!"
        }
    )
    url = FileField(
        label='文件',
        validators=[
            DataRequired("请上传文件!")
        ],
        description="文件",
    )
    info = TextAreaField(
        label='简介',
        validators=[
            DataRequired("请输入简介!")
        ],
        description="简介",
        render_kw={
            "class": "form-control",
            "rows": "10",
            "id": "input_info",
        }
    )

    logo = FileField(
        label='封面',
        validators=[
            DataRequired("请上传封面!")
        ],
        description="封面",
    )
    star = SelectField(
        label='星级',
        validators=[
            DataRequired("请选择星级!")
        ],
        coerce=int,
        choices=[(1, '1星'), (2, '2星'), (3, '3星'), (4, '4星'), (5, '5星')],
        description="星级",
        render_kw={
            "class": "form-control",
        }
    )
    tag_id = SelectField(
        label='标签',
        validators=[
            DataRequired("请选择标签!")
        ],
        coerce=int,
        choices=[(v.id, v.name) for v in tags],
        description="标签",
        render_kw={
            "class": "form-control",
        }
    )
    area = StringField(
        label='地区',
        validators=[
            DataRequired("请输入地区!")
        ],
        description="地区",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入地区!"
        }
    )
    length = StringField(
        label='片长',
        validators=[
            DataRequired("请输入片长!")
        ],
        description="片长",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入片长!"
        }
    )
    release_time = StringField(
        label='上映时间',
        validators=[
            DataRequired("请选择上映时间!")
        ],
        description="上映时间",
        render_kw={
            "class": "form-control",
            "id": "input_release_time",
            "placeholder": "请选择上映时间!"
        }
    )
    submit = SubmitField(
        '编辑',
        render_kw={
            "class": "btn btn-primary"
        }
    )

    def validate_title(self, field):
        title = field.data
        num = Movie.query.filter_by(title=title).count()
        if num > 0:
            raise ValidationError("该电影已存在!")

在app初始化文件中定义上传文件的目录

app.config['UP_DIR'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static/uploads/')
添加电影

视图函数
文件名称检测

from werkzeug.utils import secure_filename

def change_filename(filename):
    fileinfo = os.path.splitext(filename)
    filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(uuid.uuid4().hex) + fileinfo[-1]
    return filename
@admin.route('/movie/add/', methods=['GET', 'POST'])
@admin_login_req
def movie_add():
    form = MovieForm()
    if form.validate_on_submit():
        data = form.data
        file_url = secure_filename(form.url.data.filename)
        file_logo = secure_filename(form.logo.data.filename)

        if not os.path.exists(app.config['UP_DIR']):
            os.makedirs(app.config['UP_DIR'])
            os.chmod(app.config['UP_DIR'], 6)

        url = change_filename(file_url)
        logo = change_filename(file_logo)
        form.url.data.save(app.config['UP_DIR'] + url)
        form.logo.data.save(app.config['UP_DIR'] + logo)

        movie = Movie(
            title=data['title'],
            url=url,
            info=data['info'],
            logo=logo,
            star=int(data['star']),
            playnum=0,
            commentnum=0,
            tag_id=int(data['tag_id']),
            area=data['area'],
            release_time=data['release_time'],
            length=data['length']
        )
        db.session.add(movie)
        db.session.commit()
        flash('电影添加成功!', 'info')
        return redirect(url_for('admin.movie_add'))
    return render_template('admin/movie_add.html', form=form)

app/templates/admin/movie_add.html

{% extends 'admin/admin.html' %}

{% block content %}
    <section class="content-header">
        <h1>微电影管理系统</h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> 电影管理</a></li>
            <li class="active">添加电影</li>
        </ol>
    </section>
    <section class="content" id="showcontent">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">添加电影</h3>
                    </div>
                    <form role="form" method="post" enctype="multipart/form-data">
                        <div class="box-body">
                            {% for message in get_flashed_messages(category_filter=['info']) %}
                                <div class="alert alert-success alert-dismissible">
                                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
                                    </button>
                                    <h4><i class="icon fa fa-check"></i> 操作成功!</h4>
                                    {{ message }}
                                </div>
                            {% endfor %}
                            <div class="form-group">
                                <label for="input_title">{{ form.title.label }}</label>
                                {{ form.title }}
                                {% for err in form.title.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_url">{{ form.url.label }}</label>
                                {{ form.url }}
                                {% for err in form.url.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                                <div style="margin-top:5px;">
{#                                    <div id="moviecontainer"></div>#}
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="input_info">{{ form.info.label }}</label>
                                {{ form.info }}
                                {% for err in form.info.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_logo">{{ form.logo.label }}</label>
                                {{ form.logo }}
                                {% for err in form.logo.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
{#                                <img data-src="holder.js/262x166" style="margin-top:5px;" class="img-responsive"#}
{#                                     alt="">#}
                            </div>
                            <div class="form-group">
                                <label for="input_star">{{ form.star.label }}</label>
                                {{ form.star }}
                                {% for err in form.star.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_tag_id">{{ form.tag_id.label }}</label>
                                {{ form.tag_id }}
                                {% for err in form.tag_id.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_area">{{ form.area.label }}</label>
                                {{ form.area }}
                                {% for err in form.area.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_length">{{ form.length.label }}</label>
                                {{ form.length }}
                                {% for err in form.length.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_release_time">{{ form.release_time.label }}</label>
                                {{ form.release_time }}
                                {% for err in form.release_time.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                        </div>
                        <div class="box-footer">
                            {{ form.csrf_token }}
                            {{ form.submit }}
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
{% endblock %}
电影列表

视图函数

@admin.route('/movie/list/<int:page>/')
@admin_login_req
def movie_list(page=1):
    if page <= 0:
        page = 1
    page_data = Movie.query.join(Tag).filter(
        Tag.id == Movie.tag_id
    ).order_by(
        Movie.addtime.desc()
    ).paginate(page=page, per_page=10)
    return render_template('admin/movie_list.html', page_data=page_data)

app/templates/admin/movie_list.html

{% extends 'admin/admin.html' %}
{% from 'ui/admin_page.html' import pagination %}
{% block content %}
    <section class="content-header">
        <h1>微电影管理系统</h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> 电影管理</a></li>
            <li class="active">电影列表</li>
        </ol>
    </section>
    <section class="content" id="showcontent">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title">电影列表</h3>
                        <div class="box-tools">
                            <div class="input-group input-group-sm" style="width: 150px;">
                                <input type="text" name="table_search" class="form-control pull-right"
                                       placeholder="请输入关键字...">

                                <div class="input-group-btn">
                                    <button type="submit" class="btn btn-default"><i class="fa fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="box-body table-responsive no-padding">
                        {% for message in get_flashed_messages(category_filter=['info']) %}
                            <div class="alert alert-success alert-dismissible">
                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
                                </button>
                                <h4><i class="icon fa fa-check"></i> 操作成功!</h4>
                                {{ message }}
                            </div>
                        {% endfor %}
                        <table class="table table-hover">
                            <tbody>
                            <tr>
                                <th>编号</th>
                                <th>片名</th>
                                <th>片长</th>
                                <th>标签</th>
                                <th>地区</th>
                                <th>星级</th>
                                <th>播放数量</th>
                                <th>评论数量</th>
                                <th>上映时间</th>
                                <th>操作事项</th>
                            </tr>
                            {% for data in page_data.items %}

                                <tr>
                                    <td>{{ data.id }}</td>
                                    <td>{{ data.title }}</td>
                                    <td>{{ data.length }}分钟</td>
                                    <td>{{ data.tag.name }}</td>
                                    <td>{{ data.area }}</td>
                                    <td>{{ data.star }}</td>
                                    <td>{{ data.playnum }}</td>
                                    <td>{{ data.commentnum }}</td>
                                    <td>{{ data.release_time }}</td>
                                    <td>
                                        <a href="{{ url_for('admin.movie_edit', id=data.id) }}" class="label label-success">编辑</a>
                                        &nbsp;
                                        <a href="{{ url_for('admin.movie_del', id=data.id) }}"
                                           class="label label-danger">删除</a>
                                    </td>
                                </tr>
                            {% endfor %}

                            </tbody>
                        </table>
                    </div>
                    <div class="box-footer clearfix">
                        {{ pagination(page_data, 'admin.movie_list') }}
                    </div>
                </div>
            </div>
        </div>
    </section>
{% endblock %}

{% block js %}
    <script>
        $(document).ready(function () {
            $('#g-3').addClass('active');
            $('#g-3-2').addClass('active');
        })
    </script>
{% endblock %}

修改app/templates/admin/grid.html

<li id="g-3-2">
    <a href="{{ url_for('admin.movie_list', page=1) }}">
        <i class="fa fa-circle-o"></i> 电影列表
    </a>
</li>
删除电影

视图函数

@admin.route('/movie/del/<int:id>/')
@admin_login_req
def movie_del(id=None):
    movie = Movie.query.get_or_404(int(id))
    db.session.delete(movie)
    db.session.commit()
    flash('电影删除成功!', 'info')
    return redirect(url_for('admin.movie_list', page=1))

修改一下前端删除按钮a标签

修改电影

视图函数

@admin.route('/movie/edit/<int:id>', methods=['GET', 'POST'])
@admin_login_req
def movie_edit(id=None):
    form = MovieForm()

    # # 如果不设置,默认依然会让上传文件
    # form.url.flags.required = False
    # form.logo.flags.required = False

    # # 取消校验,可能没有上传文件
    # form.url.validators=[]
    # form.logo.validators=[]
    # 取消后如果没有上传文件,form.url.data是一个str对象
    # 上传文件后是才是一个文件对象
    # 为了方便,设置必须上传文件

    movie=Movie.query.get_or_404(int(id))
    if  request.method =='GET':
        form.info.data = movie.info
        form.tag_id.data = movie.tag_id
        form.star.data = movie.star
    if form.validate_on_submit():
        data = form.data
        movie_count = Movie.query.filter_by(title=data['title']).count()
        if movie_count == 1 and movie.title != data['title']:
            flash('该电影已存在!', 'error')
            return redirect(url_for('admin.movie_edit', id=id))

        if not os.path.exists(app.config['UP_DIR']):
            os.makedirs(app.config['UP_DIR'])
            os.chmod(app.config['UP_DIR'], 6)

        if form.url.data.filename !='':
            file_url = secure_filename(form.url.data.filename)
            movie.url = change_filename(file_url)
            form.url.data.save(app.config['UP_DIR'] + movie.url)

        if form.logo.data.filename != '':
            file_logo = secure_filename(form.logo.data.filename)
            movie.logo = change_filename(file_logo)
            form.logo.data.save(app.config['UP_DIR'] + movie.logo)

        movie.star = data['star']
        movie.tag_id = data['tag_id']
        movie.info = data['info']
        movie.title = data['title']
        movie.area = data['area']
        movie.length = data['length']
        movie.release_time = data['release_time']

        db.session.add(movie)
        db.session.commit()
        flash('电影修改成功!', 'info')
        return redirect(url_for('admin.movie_add', id=movie.id))
    return render_template('admin/movie_edit.html', form=form, movie=movie)

app/templates/admin/movie_edit.html

{% extends 'admin/admin.html' %}

{% block content %}
    <section class="content-header">
        <h1>微电影管理系统</h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> 电影管理</a></li>
            <li class="active">修改电影</li>
        </ol>
    </section>
    <section class="content" id="showcontent">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">修改电影</h3>
                    </div>
                    <form role="form" method="post" enctype="multipart/form-data">
                        <div class="box-body">
                            {% for message in get_flashed_messages(category_filter=['info']) %}
                                <div class="alert alert-success alert-dismissible">
                                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
                                    </button>
                                    <h4><i class="icon fa fa-check"></i> 操作成功!</h4>
                                    {{ message }}
                                </div>
                            {% endfor %}
                            {% for message in get_flashed_messages(category_filter=['error']) %}
                                <div class="alert alert-danger alert-dismissible">
                                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×
                                    </button>
                                    <h4><i class="icon fa fa-ban"></i> 操作失败!</h4>
                                    {{ message }}
                                </div>
                            {% endfor %}
                            <div class="form-group">
                                <label for="input_title">{{ form.title.label }}</label>
                                {{ form.title(value=movie.title) }}
                                {% for err in form.title.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_url">{{ form.url.label }}</label>
                                {{ form.url }}
                                {% for err in form.url.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                                <div style="margin-top:5px;">
                                    <div id="moviecontainer"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="input_info">{{ form.info.label }}</label>
                                {{ form.info }}
                                {% for err in form.info.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_logo">{{ form.logo.label }}</label>
                                {{ form.logo }}
                                {% for err in form.logo.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                                <img src="{{ url_for('static', filename='uploads/'+movie.logo) }}" style="margin-top:5px;" class="img-responsive"
                                     alt="">
                            </div>
                            <div class="form-group">
                                <label for="input_star">{{ form.star.label }}</label>
                                {{ form.star }}
                                {% for err in form.star.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_tag_id">{{ form.tag_id.label }}</label>
                                {{ form.tag_id }}
                                {% for err in form.tag_id.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_area">{{ form.area.label }}</label>
                                {{ form.area(value=movie.area) }}
                                {% for err in form.area.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_length">{{ form.length.label }}</label>
                                {{ form.length(value=movie.length) }}
                                {% for err in form.length.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                            <div class="form-group">
                                <label for="input_release_time">{{ form.release_time.label }}</label>
                                {{ form.release_time(value=movie.release_time) }}
                                {% for err in form.release_time.errors %}
                                    <div class="col-md-12" style="color: red">{{ err }}</div>
                                {% endfor %}
                            </div>
                        </div>
                        <div class="box-footer">
                            {{ form.csrf_token }}
                            {{ form.submit }}
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
{% endblock %}

{% block js %}
    <script src="{{ url_for('static',filename='jwplayer/jwplayer.js') }}"></script>
    <script type="text/javascript">
        jwplayer.key = "P9VTqT/X6TSP4gi/hy1wy23BivBhjdzVjMeOaQ==";

    </script>
    <script type="text/javascript">
        jwplayer("moviecontainer").setup({
            flashplayer: "{{ url_for('static',filename='jwplayer/jwplayer.flash.swf') }}",
            playlist: [{
                file: "{{ url_for('static', filename='uploads/'+movie.url) }}",
                title: "{{ movie.title }}"
            }],
            modes: [{
                type: "html5"
            }, {
                type: "flash",
                src: "{{ url_for('static',filename='jwplayer/jwplayer.flash.swf') }}"
            }, {
                type: "download"
            }],
            skin: {
                name: "vapor"
            },
            "playlist.position": "left",
            "playlist.size": 200,
            height: 250,
            width: 387,
        });

    </script>
    <script>
        $(document).ready(function () {
            $('#input_release_time').datepicker({
                autoclose: true,
                format: 'yyyy-mm-dd',
                language: 'zh-CN',
            });
        });

    </script>
    <script>
        $(document).ready(function () {
            $('#g-3').addClass('active');
            $('#g-3-1').addClass('active');
        })
    </script>
{% endblock %}

修改电影列表中的编辑按钮

<a href="{{ url_for('admin.movie_edit', id=data.id) }}" class="label label-success">编辑</a>

预告管理

创建预告表单

class PreviewForm(FlaskForm):
    title = StringField(
        label='预告标题',
        validators=[
            DataRequired("请输入预告标题!")
        ],
        description="预告标题",
        render_kw={
            "class": "form-control",
            "placeholder": "请输入预告标题!"
        }
    )
    logo = FileField(
        label='预告封面',
        validators=[
            DataRequired("请上传预告封面!"),
        ],
        description="预告封面",
    )
    submit = SubmitField(
        '编辑',
        render_kw={
            "class": "btn btn-primary"
        }
    )

    def validate_title(self, field):
        title = field.data
        num = Preview.query.filter_by(title=title).count()
        if num > 0:
            raise ValidationError("该预告已存在!")
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容