Answer the question
In order to leave comments, you need to log in
Flask-WTF: how to save model with One-to-Many relationship to database?
There are two Datacener and Server models with a common ForeigKey relationship, when trying to create a new Server model, the form fails validation. When outputting to the form.errors template, I get "Datacener: Not a valid choice".
class Datacener(db.Model):
id = db.Column(db.Integer, primary_key=True)
server = db.relationship('Server', backref='datacener', 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('datacener.id'), nullable=False)
@app.route('/add_server', methods = ['POST', 'GET'])
@login_required
def add_server():
form = ServerForm(request.form)
if request.method=='POST' and form.validate():
data = Server(
number=form.number.data,
name=form.name.data,
factory=form.factory.data,
model=form.model.data,
serial=form.serial.data,
os=form.os.data,
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('Datacener', choices=[(x.id, x.name) for x in db.session.query(Datacener).all()])
class ServerForm(FlaskForm):
number = IntegerField('Number')
name = StringField('Name')
factory = StringField('Factory')
model = StringField('Model')
serial = IntegerField('Serial')
os = StringField('OS')
datacener_id = SelectField()
#datacener_id = SelectField('Datacener', choices=[(x.id, x.name) for x in db.session.query(Datacener).all()])
def __init__(self, *args, **kwargs):
self.datacener_id.kwargs['choices'] = [(x.id, x.name) for x in db.session.query(Datacener).all()]
FlaskForm.__init__(self, *args, **kwargs)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question