Search code examples
pythondictionarywtformsflask-wtformsformfield

Wtforms- Create Dict using formfield that has two values per key


I'd like to be able to collect both the track name and the start time for each track on a cd into a dict or json column in a table. I have defined a formfield to catch the data relating to the track names and save it in a dict:

class SeperateTracks(NoCsrfForm):
        track1 = TextField('track1')
        track2 = TextField('track2')
        track3 = TextField('track3')
        track4 = TextField('track4')

class SendForm(Form):
        alltracks = FormField(SeperateTracks)

This creates a dictionary that looks something like this so:

{"track1": "songname1", "track2": "songname2", "track3": "songname3", "track4": "songname4"}

What I'd like to achieve, is to have two TextFields per track- one for the track name and one for the start time of the track. I realize that in terms of creating more fields to accomodate this, I could simply create more text fields to hold the start time data like so:

class SeperateTracks(NoCsrfForm):
        track1 = TextField('track1')
        track2 = TextField('track2')
        track3 = TextField('track3')
        track4 = TextField('track4')
        starttime1 = TextField('starttime1')
        starttime2 = TextField('starttime2')
        starttime3 = TextField('starttime3') 
        starttime4 = TextField('starttime4')

However, this wouldn't associate the times with the corresponding tracks. What would be the recommended method for doing something like this?


Solution

  • You'd want something like this:

    class Track(NoCsrfForm):
        songname = StringField('Song Name')
        starttime = StringField('start time')
    
    class SeparateTracks(NoCsrfForm):
        tracks = FieldList(FormField(Track), min_entries=1, max_entries=4)
    

    I made assumptions on max_entries based on your example, but it's not strictly required, and you can manage anywhere between 1 and N entries this way.

    the data in python would look something like:

    [{songname: "name 1", starttime: "123"}, {songname: "name 2", starttime: "456"}, ... ]
    

    More info: