我是 Flask 的新手,对它的数据库建模有点困惑。如果无论如何这不是一个有资格发布的问题,请原谅。
我需要在 Flask 中创建一个多选模型字段,并且我需要能够从后端管理面板访问它并为其设置值。它确实在带有 WTF 表单的文档中显示选项以创建多项选择字段。我很困惑如何创建附加到数据库的表单。有人可以为我解决这个问题吗,因为我是 Django 用户,在 Django Forms 和 ModelForms 中有不同的方法,所以试图了解它在 Flask 中会是什么。如何在 Flask 中呈现基于数据库的表单?我将如何创建一个多选字段并为其创建数据库。请帮忙。
请您参考如下方法:
您正在寻找的是 SQLAlchemy 内置 ORM,用于从模型构建表单或集成到数据库。在需要时,还有其他选项可以克服 Flask ORM 的限制。以下示例可以让您更加清楚。
from flask import Flask, render_template, redirect, flash
from flask.wtf import Form
from flask.ext.sqlalchemy import SQLAlchemy
from wtf.ext.sqlalchemy.orm import model_form
app=Flask(__app__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/employees.sqlite'
app.config['SQLALCHEMY_ECHO'] = True
# Here you initiate the ext
db=SQLAlchemy(app)
#Let's define a model
class Employee(db.Model)
__tablename__ = 'employee'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False
birthday = db.Column(db.Date, nullable=False
def __repr__(self):
return 'employee %s' %self.name
# Now go to your shell inside your env not in gloabal shell outside your env and run this command.
# From your .py file where you've created all above configration first make an import to db from shell
from file.py import db
#Then create a database with following command in shell
db.create.all()
#Your auto generated database based form below
EmployeeForm() = model_form(Employee, base_class=Form, field_args{'name':{'class':'employee'}})
#Let's create a view with model_form or database based form in your case.
@app.route('/', methods=['GET', 'POST'])
def index()
#request.POST does same in Django or any other Python based web framework like Bottle, Tornado etc
form = EmployeeForm()
try:
if form_validate_on_submit():
employee=Employee() #load the model values
form.populate_obj(Employee) #populates the form with respective values
db.session.add(employee) #gathers the session based data to be added in DB
db.session.commit() #Adds data to DB
flash('New Employee added to database successfully.') #Display a message to end user at front end.
retrun redirect('/') # redirects upon success to your homepage.
except Exception e:
# logs the errors
db.session.rollback()
flash('There was a problem registering new employee. Please contact the site administrator at site@site.com')
employee_list = Employe.query.all() #equailent to django style "item.objects.all() to show list of all existing items.
return render_template('index.html', form=form, employee_list=employee_list)
在上面的最后一行中,您做了三件事。您像在 Django 中一样将表单变量或上下文变量作为 "form" 获取,以便您的最终用户可以输入数据。 然后您将模型数据保存在数据库中,作为 "employee_list=employee_list" 将向最终用户显示所有列表。 "flash" 就像 Django 消息传递框架。
现在对于多项选择,它的模型与 djagno choice argument 的键值相同,如下所示: 根据我的经验,我建议您为 Python 连接的数据库安装一个简单的 ORM“peewee”。
choices = (('key', 'value')('key', 'value'))
employee_type = db.Model(db.String(90), choices=('key1', 'key2)
希望这对您有所帮助。
