Вопрос

I'm trying to create two views using Flask. The first view show_entries displays a list of entries in a table. It also includes a form to create new entries.

The form gets submitted to a second view new_entry which accepts the POST method and is responsible for adding the new entry to the table using SQLAlchemy. new_entry then redirects back to show_entries.

My problem is that form.errors are not routed to show_entries, so the user never sees them. I'm not sure of the best way to go about this, or if I'm even on the right track with the way I've divided up the views.

Here's what I currently have:

def show_entries():
    entryForm = EntryForm()
    entries = g.user.entries
    return render_template('show_entries.html', 
                           entries=entries,
                           entryForm=entryForm)

def new_entry():
    form = EntryForm()
    if form.validate_on_submit():
        newEntry = Entry(g.user, form.time.data)
        db_session.add(newEntry)
        db_session.commit()
        flash('New entry was succesfully posted')
    return redirect(url_for('show_entries'))
Это было полезно?

Решение

The normal pattern is to have /show_entries as a listing page with new_entry as the form. When you do a GET request to new_entry you get the form, then POST to it to add the entry. That way if there's an error you can just show it next to the form - all the data is available. If you split the views as you have then you'll need some way of moving the error data (and form data) from the new_entry view to the show_entries view.

Something more like (untested):

def show_entries():
    entries = g.user.entries
    return render_template('show_entries.html', 
                           entries=entries)

def new_entry():
    form = EntryForm()
    if form.validate_on_submit():
        newEntry = Entry(g.user, form.time.data)
        db_session.add(newEntry)
        db_session.commit()
        flash('New entry was successfully posted')
        return redirect(url_for('show_entries'))
    return render_template('show_new_entry_form.html', 
                           entryForm=form)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top