문제

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