flask-sqlalchemy+wtforms实现标签动态更新

解决循环导入的问题

我的目录结构:
flask-sqlalchemy+wtforms实现标签动态更新_第1张图片

  1. 创建一个ext.py将db的初始化隔离

    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    
  2. 在实例化form对象时再传入db

    from flask import Blueprint, request, render_template
    from app01.ext import db
    from app01.views.user.forms import LoginForm
    
    blue_user = Blueprint('user', __name__, template_folder='./templates', url_prefix='/user')
    
    
    @blue_user.route('/', methods=['get', 'post'])
    def index():
        if request.method == 'GET':
            form = LoginForm(db=db)
            return render_template('html.html', form=form)
        else:
            form = LoginForm(formdata=request.form,db=db)
            print(form.validate())
            print(form.data)
            print(form.errors)
            return render_template('html.html', form=form)
    

动态更新标签

from wtforms import widgets, validators, Form
from wtforms.fields import simple, html5, core
from app01.views.user import models


class LoginForm(Form):
    def __init__(self, db=None, **kwargs):
        super().__init__(**kwargs)
        self.name.choices = db.session.query(models.User.id, models.User.username).order_by('id').all()

    name = core.SelectMultipleField(
        label='城市',
        choices=[],
        coerce=int
    )
  1. 每次实例化form即每次请求时从数据库拿到数据
  2. coerce=int

对于俺这种小白来说,sqlalchemy太容易出现循环导入了,所以干脆把实例化踢出去比较好。导包都能死锁,我也是醉了,搞得一个头两个大。T_T

你可能感兴趣的:(flask,flask,python,后端)