Retreive Empty String from null form data following failed validation

Viewed 225

This is more of a python question than a wtforms question and the summary at the bottom will probably make more sense to people who usually answer pure python questions. When a page validates and one field fails validation, I've managed to get my script to hold onto the previously entered values by making use of the if/else statement. It allows the user to see what they typed in before the validation error was triggered:

 if request.method == 'POST':
                if form.validate_on_submit():
                        try:
                                models.insert(form)
                        except:
                                return redirect(url_for('failure'))
                        else:
                                return redirect(url_for('success'))
                else:
                        number_of_discs = form.number_of_discs.data
                        number_of_parts = form.number_of_parts.data
                        disc_number = form.disc_number.data
                        tx_date = form.tx_date.data
                        start_time_1 = form.start_time_1.data
                        end_time_1 = form.end_time_1.data
                        start_time_2 = form.start_time_2.data
                        end_time_2 = (form.data.get('end_time_2', '')) 

However, if one of the fields is then left empty, and the validation error is triggered a second by another incorrectly filled field, the value in the empty field now shows up as 'None'. In a way, this is by design as I would like the database to be updated with NULL values rather than empty strings. However, during this part of the process- i.e. the form validation, I would like the field to show up as empty.

So to summarize, how can I change the line:

number_of_discs = form.number_of_discs.data

so that number_of_discs contains the data in form.number_of_discs.data, except when it is null, in which case it should contain an empty string.

1 Answers
Related