我的目录结构:
-
创建一个ext.py将db的初始化隔离
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
-
在实例化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 )
- 每次实例化form即每次请求时从数据库拿到数据
- coerce=int
对于俺这种小白来说,sqlalchemy太容易出现循环导入了,所以干脆把实例化踢出去比较好。导包都能死锁,我也是醉了,搞得一个头两个大。T_T
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)