0
votes

I have the following code:

class ReconForm(Form):
    compressedFilePath = StringField('Compressed File Path', [validators.Required()] )

and I instantiate it like this:

form = ReconForm()
form.compressedFilePath.default = 'hey'

It does nothing. It used to set the default value to hey but then it stopped and I have no idea why.

If I print form.compressedFilePath.default then it prints the correct value. If I set a default in the field constructor the template renders the correct value. Otherwise it just does nothing and it's driving me crazy.

What am I doing wrong?

2
Have you recently installed a newer version of WTForms? - dirn
I don't think so. I changed it to .data instead of .default for a while and then changed it back and it started working again. Could it be to do with caching or something? - user1170304
I've never set the default value that way, so I wasn't aware that it ever worked. Code doesn't usually stop working on its own, though. That's why my initial thought was that perhaps you upgraded to a newer version of WTForms. - dirn

2 Answers

6
votes

Here are the two ways I know to set a default value for a field using WTForms.

  1. To set the value to be the default for all instances of a form, declare the value in the field's definition.

    class ReconForm(Form):
        compressedFilePath = StringField(
            'Compressed File Path', [validators.Required()], default='hi')
    
    form = ReconForm()
    

    To verify:

    assert 'value="hi"' in str(form.compressedFilePath)
    
  2. To set the value to be the default for just a specific instance of the form, specify the value at instantiation.

    class ReconForm(Form):
        compressedFilePath = StringField(
            'Compressed File Path', [validators.Required()])
    
    form = ReconForm(compressedFilePath='hi')
    

    To verify:

    assert 'value="hi"' in str(form.compressedFilePath)
    
1
votes

Really old question but there is an easier way - just call process() on your form after setting the default value.