[Flask] if/else - form handling code

Gergely Polonkai gergely at polonkai.eu
Mon Sep 9 09:46:50 EDT 2019


Hello,

Assuming itʼs WTForms, you might want to take a look at form.populate_obj()
(in the if branch) and form = Form(obj=ir) (before the if statement), while
completely dropping tho else clause.

The problem with your approach is that your else branch will trigger if a
POST operation is in place, but form validation fails. In such a case,
right now you drop user data and change it to the data stared in ir.

If you have multiple SQLAlchemy models you may also want to look into the
wforms-sqlalchemy package.

Best,
Gergely


On Mon, 9 Sep 2019, 15:41 Corey Boyle, <coreybrett at gmail.com> wrote:

> I have this in one of my views...
>
>         if form.validate_on_submit():
>             ir.notes = form.notes.data
>             ir.direction = form.direction.data
>             ir.insp_date = form.insp_date.data
>             ir.in_out_date = form.in_out_date.data
>             ir.customer_pk = form.customer.data
>             ir.branch_pk = form.branch.data
>             db.session.add(ir)
>             db.session.commit()
>             return redirect(url_for('sales.inspectionreport', irpk=ir.pk))
>         else:
>             form.notes.data = ir.notes
>             form.direction.data = ir.direction
>             form.insp_date.data = ir.insp_date
>             form.in_out_date.data = ir.in_out_date
>             form.customer.data = ir.customer_pk
>             form.branch.data = ir.branch_pk
>
> The else does all the same assignments as the if, but in reverse order.
>
> Is there a better way to write this?
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20190909/2e6607d7/attachment.html>


More information about the Flask mailing list