Skip to content

Instantly share code, notes, and snippets.

@roganjoshp
Created August 9, 2019 11:26
Show Gist options
  • Save roganjoshp/3929be1840566e88d7c8e13d3dd03c9e to your computer and use it in GitHub Desktop.
Save roganjoshp/3929be1840566e88d7c8e13d3dd03c9e to your computer and use it in GitHub Desktop.
Clear Flask-WTF after AJAX submission
# =============================================================================
# routes.py
# =============================================================================
@bp.route('/add_child_product', methods=['POST'])
def add_child_product():
"""
Handle form validation. If form is invalid, re-render form with validation
errors. If the form is valid, update product spec table, close modal and
reset form.
"""
new_child_form = NewChildForm()
if new_child_form.validate_on_submit():
parent_code = new_child_form.parent_product_code.data
# Process form here
# Reset the form
new_child_form.reset()
return jsonify({'template': render_template(
PROD_SPEC + 'product_specifications.html',
new_child_form=new_child_form,
product_code=parent_code,
success=True), # In place of flash
'success': True})
else:
return jsonify({'template': render_template(
PROD_SPEC + 'new_child_form.html',
new_child_form=new_child_form,
product_code=new_child_form.parent_product_code.data,
success=False
),
'success': False})
# =============================================================================
# forms.py
# =============================================================================
from werkzeug.datastructures import MultiDict
class NewChildForm(FlaskForm):
parent_product_code = HiddenField()
new_product_code = IntegerField('Product Code',
validators=[DataRequired()])
product_qty = FloatField('Child Quantity', validators=[DataRequired()])
submit = SubmitField('Add Child')
# Validation methods here
def reset(self):
"""
Reset all fields and avoid validation errors, but pre-populate hidden
field
"""
blank_data = MultiDict([('parent_product_code',
self.parent_product_code)])
self.process(blank_data)
# =============================================================================
# template.html
# =============================================================================
<script>
$("#add_new_child").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
// Avoid CSRF issues by not including token in the form itself
var csrf_token = "{{ csrf_token() }}";
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
context: form,
success: function(resp) {
if (resp['success'] == true) {
$('#product_spec_div').html(resp['template']);
$(".modal-fade").modal("hide");
$('body').removeClass('modal-open');
$(".modal-backdrop").remove();
} else {
$('#form_new_child').html(resp['template']);
}
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment