【问题标题】:calling wtforms from sqlalchemy in flask从烧瓶中的 sqlalchemy 调用 wtforms
【发布时间】:2014-06-23 14:53:26
【问题描述】:

我正在构建一个包含多个调查表的网站。

class A(Form):
    name = Text('Name')

class B(Form):
    name = Text('Name')

class C(Form):
    name = Text('Name')

etc...

我有一个包含所有这些表格信息的模型:

class forms(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(64), unique=True)
    description = db.Column(db.String(255))
    wtform = ???db.Column(db.String(255))??? # How to store a wtform [A, B, C, etc...]?

用户可以从菜单中选择特定的表单并被引导至:

@app.route('/new/<int:id>', methods = ['GET', 'POST'])
@login_required
def new(id):

    data = forms.query.get(id)

    form = data.???wtform???  # How to call the particular wtform here? 

我不确定如何从 sqlalchemy 存储和调用 wtform 类。处理这种情况的最佳方法是什么?我是否应该为每个表单使用多个 @app.route('/A')、@app.route('/B')、@app.route('/C') 调用,这会增加冗余,或者我可以将整个 wtform 类结构存入数据库?

【问题讨论】:

    标签: flask sqlalchemy wtforms


    【解决方案1】:

    您已经在代码中定义了表单,因此没有理由也将它们存储在数据库中。存储要使用的表单的引用,然后根据引用实例化正确的表单。

    class FormDef(Base):
        __tablename__ = 'form_def'
    
        id = Column(Integer, primary_key=True)
        name = Column(String, nullable=False, unique=True)
        description = Column(String, nullable=False, default='')
        form_ref = Column(String, nullable=False)  # will be the name of the form class in this example
    
    def get_form(instance):
        # given an instance of FormDef, get the form class with the name stored in form_ref
        from my_package import forms  # or wherever your forms are stored
    
        return getattr(forms, instance.form_ref)
    

    附带说明一下,将表单类信息存储在行中似乎不是解决您要解决的问题的正确方法。

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 1970-01-01
      • 2012-12-29
      • 2016-05-03
      • 1970-01-01
      • 2014-07-05
      • 2020-07-24
      • 2021-01-24
      • 2016-01-23
      相关资源
      最近更新 更多