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

flask-sqlalchemy+wtforms实现标签动态更新,第1张

flask-sqlalchemy+wtforms实现标签动态更新 解决循环导入的问题

我的目录结构:

  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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5158420.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存