我有一个Flask-WTF表单,其中包含用于选择相关对象的选项字段。当我尝试验证表单时,form.errors
始终显示“Datacener:Not a valid choice”。
class Datacenter(db.Model):
id = db.Column(db.Integer, primary_key=True)
server = db.relationship('Server', backref='datacenter', lazy=True)
tier = db.Column(db.Integer)
class Server(db.Model):
id = db.Column(db.Integer, primary_key=True)
os = db.Column(db.String(64))
datacener_id=db.Column(db.Integer, db.ForeignKey('datacenter.id'), nullable=False)
class ServerForm(FlaskForm):
datacener_id = SelectField('Datacener', choices=[(x.id, x.name) for x in db.session.query(Datacener).all()])
@app.route('/add_server', methods = ['POST', 'GET'])
def add_server():
form = ServerForm(request.form)
if request.method=='POST' and form.validate():
data = Server(datacener_id=form.datacener_id.data)
db.session.add(data)
db.session.commit()
flash('Server created successfully!')
return redirect('/')
return render_template('new_server.html', form=form)
我假设这不起作用,因为模型之间的一对多关系。因为没有此连接的相同表单可以正常工作。
----编辑形式---
class ServerForm(FlaskForm):
number = IntegerField('Number')
name = StringField('Name')
factory = StringField('Factory')
model = StringField('Model')
serial = IntegerField('Serial')
os = StringField('OS')
datacener_id = SelectField()
def __init__(self, *args, **kwargs):
self.datacener_id.kwargs['choices'] = [(x, x) for x in session.get('datacener', ('not set',))]
FlaskForm.__init__(self, *args, **kwargs)