Home > Net >  Flask form submit both succeeds and errors
Flask form submit both succeeds and errors

Time:11-29

I have a flask form which works perfect and stores values in my database, but it seems to both succeed (posts values to the database and shows success flash) and fails (shows error and doesn't redirect).

view.py

from flask import render_template, Blueprint, request, redirect, url_for, flash
from project import db
from .models import Items
from .forms import ItemsForm


items_blueprint = Blueprint('items', __name__, template_folder='templates')


@items_blueprint.route('/', methods=['GET', 'POST'])
def all_items():
    all_user_items = Items.query.filter_by()
    return render_template('all_items.html', items=all_user_items)


@items_blueprint.route('/add', methods=['GET', 'POST'])
def add_item():
    form = ItemsForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                new_item = Items(form.name.data, form.notes.data)
                db.session.add(new_item)
                db.session.commit()
                flash('Item added', 'success')
                return redirect(url_for('all_items'))
            except:
                db.session.rollback()
                flash('Something went wrong', 'error')
    return render_template('add_item.html', form=form)

Output Example

enter image description here

What might be causing this, as I thought it would be one or the other.

CodePudding user response:

I looked into it because of the @NoCommandLine answer. The point is, that the all_items function is located in the blueprint, not in the base of the application. To redirect to it you want to write redirect(url_for(".all_items") (notice the full stop at the first position of the string).See the documentation for url_for, there is an example for a blueprint containing an index function. The full stop makes it search in the same blueprint the current route is in.

CodePudding user response:

It all depends on where the error occurred. Since it flashed - ('Item added', 'success'), it means your error is on the line redirect(url_for('all_items')).

You should look at the code for redirect(url_for('all_items')) and check if there is an issue with all_user_items = Items.query.filter_by(). Maybe that query is faulty. You can also try to print out the error in the except block to see what it is

  • Related