Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a WTForms CheckboxInput in Jinja Template

I can't seem to figure out how to render a WTForms CheckboxInput in my template. When I try to render the field using Flask in my Jinja template I get this error:

TypeError: call() takes exactly 2 arguments (1 given)

The error has to do with how {{ form.prefs(value='n') }} is used in my template. The WTForms documentation for CheckBoxInput says "The value= HTML attribute by default is ‘y’ unless otherwise specified by value= at rendering." I get an error whether I specify a value or not.

I can't seem to find an example of how to render a simple CheckBoxInput. Any help is appreciated.

Here's my form:

class PreferencesForm(Form):
    prefs = widgets.CheckboxInput()

Here's my template:

{% extends "base.html" %}

{% block content %}

<form method="POST" action="/user/prefs/">
    <div>{{ form.prefs(value='n') }}</div>
    <button type="submit" class="btn">Submit</button>    
</form>

{% endblock %}
like image 635
Raj Avatar asked Dec 07 '25 10:12

Raj


2 Answers

You are actually supposed to use a BooleanField instead of directly using the widget:

class PreferencesForm(Form):
    prefs = BooleanField()

And then in your template:

{{ form.prefs(value='n') }}

The general idea is to use one of the fields in your form class, which will automatically assign the proper widget for display. And widgets are:

... classes whose purpose are to render a field to its usable representation, usually XHTML. When a field is called, the default behaviour is to delegate the rendering to its widget. This abstraction is provided so that widgets can easily be created to customize the rendering of existing fields.

emphasis mine

Further, a widget needs a field instance to render itself:

def __call__(self, field, **kwargs):
    if getattr(field, 'checked', field.data):
        kwargs['checked'] = True
    return super(CheckboxInput, self).__call__(field, **kwargs)
like image 115
bool.dev Avatar answered Dec 09 '25 23:12

bool.dev


use checked att

{% if r.renovacion == 's' %}
        <td>{{  forma.renovacion(id = "" + r.id|string  + "", value = 's', checked = True) }}</td>
        {% else %}
        <td>{{  forma.renovacion(id = "" + r.id|string  + "", value = 'n', checked = False) }}</td>
        {% endif %}
like image 25
Luis Garcia Avatar answered Dec 10 '25 01:12

Luis Garcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!