A
A
Anton Degtyarev2018-07-12 23:24:19
Python
Anton Degtyarev, 2018-07-12 23:24:19

Python, Flask. How to fill forms with data from the database?

Good evening.
I'm trying to make a page for editing the properties of a certain sensor (s).
Tell me how you can fill in the forms with existing data in the database?
Now the code looks like this:
forms.py

class EditSensorForm(FlaskForm):
    w1_addr = StringField('1-wire адрес', validators=[DataRequired()])
    pin = StringField('Пин')
    function = StringField('Функция', validators=[DataRequired()])
    place = StringField('Место', validators=[DataRequired()])
    submit = SubmitField('Подтвердить')

routes.py
@bp.route('/settings/sensors/edit/<sensor_id>', methods=['GET', 'POST'])
@login_required
def edit_sensor(sensor_id):
    sensor = Sensor.query.filter_by(id=sensor_id).first_or_404()
    form = EditSensorForm()

    if form.validate_on_submit():
        sensor.w1_addr = form.w1_addr.data
        sensor.GPIO_pin = form.pin.data
        sensor.function = form.function.data
        sensor.place = form.place.data
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('settings.sensors'))

    elif request.method == 'GET':
        form.w1_addr.data = sensor.w1_addr
        form.pin.data = sensor.GPIO_pin
        form.function.data = sensor.function
        form.place.data = sensor.place

    return render_template('/settings/edit_sensor.html',
                           form=form,
                           title='Редактирование свойств датчика')

I insert the form into the template through:
{{ wtf.quick_form(form) }}
At the output I get this
5b47b8cf6714b932468762.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
planc, 2018-07-12
@RenOoise

https://stackoverflow.com/questions/23712986/pre-p...

sensor = Sensor.query.filter_by(id=sensor_id).first_or_404()
form = EditSensorForm(obj=sensor)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question