2013-05-14 24 views
2

我似乎無法弄清楚如何在我的模板中呈現WTForms CheckboxInput。當我嘗試呈現在我的神社模板使用瓶現場我得到這個錯誤:在Jinja模板中呈現WTForms複選框輸入

類型錯誤:調用()到底需要2個參數(1給出)

誤差與{{ form.prefs(value='n') }}是怎麼做的在我的模板中使用。 CheckBoxInput的WTForms文檔中提到「默認情況下,value = HTML屬性爲'y',除非在渲染時由value =另行指定。」無論是否指定值,我都會遇到錯誤。

我似乎無法找到如何渲染一個簡單的CheckBoxInput的例子。任何幫助表示讚賞。

這裏是我的形式:

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

這裏是我的模板:

{% 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 %} 

回答

6

實際上,您應該使用一個BooleanField而不是直接使用widget的:

class PreferencesForm(Form): 
    prefs = BooleanField() 

然後在您的模板中:

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

總的想法是使用你的窗體類fields之一,它會自動分配合適的部件進行顯示。而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.

重點煤礦

而且,小部件需要field instance to render本身:

def __call__(self, field, **kwargs): 
    if getattr(field, 'checked', field.data): 
     kwargs['checked'] = True 
    return super(CheckboxInput, self).__call__(field, **kwargs) 
+1

啊!對不起,我不清楚我是不是想直接使用小部件。非常感謝你! – Raj

+0

很高興幫助! –

0

使用檢查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 %}