FlaskFM - Step 23 - Adding New Songs

I’m doing the FlaskFM project in the Build Python Web Apps with Flask.

I am having trouble with Step 23 which involves adding a new song

Below is my dashboard function code from routes.py

@app.route(’/dashboard’, methods=[“GET”, “POST”])
def dashboard():
form = SongForm()
if request.method == ‘POST’ and form.validate():
new_song = Song(title = form.title.data, artist = form.artist.data, n = 1)
db.session.add(new_song)
db.session.commit()

If i save the code and then add a new song into the dashboard view, it doesnt appear in the songs list , even after reloading. What is my mistake?

Check your database file, is your new entry in there? If so, it’s an issue of the display. If not, it’s an issue of the insertion.

You can use a GUI DB browser type app or SQL query to check the file.

I have the exact same issue. Only way I could get the code to work was to remove the and form.validate() bit from the if statement. Would love to know what was wrong with the validator. Assuming OP’s code is the same as mine:

# relevant imports from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired # SongForm definition class SongForm(FlaskForm): title = StringField(label = "Song Title:", validators=[DataRequired()]) artist = StringField(label = "Artist:", validators=[DataRequired()]) submit = SubmitField("Add Song") # non-working route definition @app.route('/dashboard', methods=["GET", "POST"]) def dashboard(): form = SongForm() if request.method == 'POST' and form.validate(): new_song = Song(title = form.title.data, artist = form.artist.data, n = 1) db.session.add(new_song) db.session.commit() else: flash(form.errors) unpopular_songs = Song.query.order_by(Song.n)[:3] songs = Song.query.all() return render_template('dashboard.html', songs = songs, unpopular_songs = unpopular_songs, form = form) # working route definition @app.route('/dashboard', methods=["GET", "POST"]) def dashboard(): form = SongForm() if request.method == 'POST': new_song = Song(title = form.title.data, artist = form.artist.data, n = 1) db.session.add(new_song) db.session.commit() else: flash(form.errors) unpopular_songs = Song.query.order_by(Song.n)[:3] songs = Song.query.all() return render_template('dashboard.html', songs = songs, unpopular_songs = unpopular_songs, form = form)

A related issue with form validation also exists in the previous project in the Learn Flask Path. Specifically the Tourist Attraction project.
It was also solved by disabling validation. Would love to know if this is reproducible if the project is done offline, to know if it is merely an issue with the CC learning environment.