1 year ago

#378132

test-img

Simon Hart

creating a flask form which uses data from another table as input

I am just beginning with python and flask and am looking to create an app. The app allows users to enter their favourite artists in one page. In the next page then allows the user to enter favourite tracks using SelectField where the artist names are given as the options.

I have the following

models:

    from application import db
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, BooleanField, IntegerField, SelectField

class Artist(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    artist_name = db.Column(db.String(45), nullable=False)
    music_artist = db.relationship('Music', backref='musicbr') 

    def __repr__(self):
        return 'Choose {}'.format(self.artist_name)

class Music(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    track_name = db.Column(db.String(45), nullable=False)
    artist_id = db.Column(db.Integer, db.ForeignKey('artist.id'), nullable=False)
    
class AddArtistForm(FlaskForm):
    artist_name = StringField('Artist Name')
    submit = SubmitField('Add Artist!')

class AddMusicForm(FlaskForm):
    track_name = StringField('Track Name')
    artist_name = SelectField('Artist Name', coerce=int)
    submit = SubmitField('Add Track!')enter code here

and the following routes

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/add_artist', methods = ['GET', 'POST'])
def add_artist():
    form = AddArtistForm()
    if form.validate_on_submit():
        new_artist = Artist(artist_name =form.artist_name.data)
        db.session.add(new_artist)
        db.session.commit()
        return render_template('index.html', message="Artist Added!")
    else:
        return render_template('add_artist.html', form=form)



   @app.route('/add_music', methods = ['GET', 'POST'])
def add_music():
    form = AddMusicForm()
    if form.validate_on_submit():
        new_track = Music(track_name =form.track_name.data)
        artist_choice = Artist.query.all(artist_name=form.artist_name.data)
        db.session.add(new_track)
        db.session.commit()
        return render_template('index.html', message="Track Added!")
    else:
        return render_template('add_music.html', form=form)

Is someone able to help me to understand what code I need to implement here?

flask

sqlalchemy

flask-wtforms

0 Answers

Your Answer

Accepted video resources