Flask實戰第51天:cms添加輪播圖後端代碼邏輯完成

首先,咱們須要給輪播圖設計一張表,由於輪播圖前端要展現,CMS要管理,因此咱們在apps下新建個models.py前端

編輯apps.models.pypython

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,不然不會進行同步json

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

表單認證,編輯cms.forms.pysession

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.pyapp

...
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())
相關文章
相關標籤/搜索