首先,我们需要给轮播图设计一张表,因为轮播图前端要展示,CMS要管理,所以我们在apps下新建个models.py
编辑apps.models.py
from exts import db
from datetime import datetime class BannerModel(db.Model):
__tablename__ = 'banner'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=False)
image_url = db.Column(db.String(255), nullable=False)
link_url = db.Column(db.String(255), nullable=False)
priority = db.Column(db.Integer, default=0)
create_time = db.Column(db.DateTime, default=datetime.now)
同步表到数据库
同步表前需要在manage.py中导入BannerModel,否则不会进行同步
python manage.py db migrate
python manage.py db upgrade
表单认证,编辑cms.forms.py
class AddBannerForm(BaseForm):
name = StringField(validators=[InputRequired(message='请输入轮播图名称!')])
image_url = StringField(validators=[InputRequired(message='请输入轮播图图片链接!')])
link_url = StringField(validators=[InputRequired(message='请输入轮播图跳转链接!')])
priority = IntegerField(validators=[InputRequired(message='请输入轮播图优先级!')])
视图,编辑cms.views.py
...
from .forms import AddBannerForm
from apps.models import BannerModel @bp.route('/abanner/',methods=['POST'])
@login_required
def abanner():
form = AddBannerForm(request.form)
if form.validate():
name = form.name.data
image_url = form.image_url.data
link_url = form.link_url.data
priority = form.priority.data
banner = BannerModel(name=name,image_url=image_url,link_url=link_url,priority=priority)
db.session.add(banner)
db.session.commit()
return xjson.json_success()
else:
return xjson.json_param_error(message=form.get_error())