Вопрос

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?

Это было полезно?

Решение

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)
    

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top