Pre-populating a BooleanField as checked (WTForms)

后端 未结 8 2739
耶瑟儿~
耶瑟儿~ 2021-02-19 04:44

For the life of me, I can\'t figure out how to pre-populate a BooleanField with WTForms. I have a field called \"active\". It defaults to being not checked, and it\'s not requ

相关标签:
8条回答
  • 2021-02-19 05:21

    If you have an object you can use it to populate your form like form = QuestionForm(obj=my_obj). If you only want to set the active attribute use form = QuestionForm(active=True).

    0 讨论(0)
  • 2021-02-19 05:21

    In addition to specifying in the template, you can likewise specify in the class definition

    class QuestionForm(Form):
        question        = TextField('Question', [validators.Required()])
        slug            = TextField('Slug'    , [validators.Required()])
        activeChecked   = BooleanField('Active', default=True  )
        activeUnChecked = BooleanField('Active', default=False )
    
    0 讨论(0)
  • 2021-02-19 05:26

    A BooleanField defined like:

    checkbox = BooleanField('title',
                  default=True,
                  render_kw ={'checked':''})
    
    0 讨论(0)
  • 2021-02-19 05:32

    I had the same problem, and after hours of searching and reading, the solution was very simple.

    form = forms.TestForm(request.form)
    form.yourbooleanfield.checked = YourVariable
    
    if request.method=="POST" and form.validate():
        print(form.yourbooleanfield.data)
    
    0 讨论(0)
  • 2021-02-19 05:38

    snahor's answer helped after much searching (+1). The google seems weak on this question. I found I needed

    <div class="form-group">
      {{adminForm.is_admin.label}}
      {{adminForm.is_admin(checked=True, class_="form-control")}}
    </div>
    
    <div class="form-group">
      {{adminForm.is_admin.label}}
      {{adminForm.is_admin(checked=False, class_="form-control")}}
    </div>
    

    which I have utilised as

    <div class="form-group">
      {{adminForm.is_admin.label}}
      {{adminForm.is_admin(checked=user.is_admin, class_="form-control")}}
    </div>
    
    0 讨论(0)
  • 2021-02-19 05:40

    To have the default boolean value as True, you need to set the default to "checked"

    Basic fields Basic fields generally represent scalar data types with single values, and refer to a single input from the form.

    class wtforms.fields.BooleanField(default field arguments, false_values=None)
    

    Represents an input type="checkbox". Set the checked-status by using the default-option. Any value for default, e.g. default="checked" puts checked into the html-element and sets the data to True

    Source

    class QuestionForm(Form):
        question = TextField('Question', [validators.Required()])
        slug = TextField('Slug', [validators.Required()])
        active = BooleanField('Active', default="checked")
    
    0 讨论(0)
提交回复
热议问题