2016-07-04 29 views
1

在我的燒瓶應用程序中,我必須在同一頁上多次繪製表單。這導致了我在頁面上有多個具有相同ID的輸入字段的問題。例如: -如何使用WTForms繪製沒有id屬性的輸入?

class ChannelForm(flask_wtf.Form): 
    name = StringField('name') 

加上這個模板:

<form> 
    {{ form.name }} 
</form> 
... 
<form> 
    {{ form.name }} 
</form> 

導致兩個輸入元素具有相同id

<input id="name" name="name" value="" type="text"> 

是否有禁用添加id屬性的官員呢?

回答

2

快速N」髒:

我發現了以下工作很好:而不是使用領域直接,我將它們包裝在一個神社宏:

{% macro render_field(field) %} 
<label> 
    <span>{{ _field.label.text }} </span> 
    {{ field(id=False, **kwargs) }} 
</label> 
{% endmacro %} 

其可以像這樣使用:

{% from "_formhelpers.html" import render_field %} 
{{ render_field(form.name) }} 

這裏的技巧是在渲染字段時通過id=False

使用元對象:

_Auto = object() 
class NoIdAttributeMeta(DefaultMeta): 
    """ 
    Surpresses rendering the `id' attribute. 
    """ 

    def bind_field(self, form, unbound_field, options): 
     """ 
     Raises TypeError in case 'id' is given as a positional arg when constructing a field. 
     If this happens, make this code smarter or pass `id' as a keyword arg. 
     """ 
     # we check `id' at rendering time and if it is still _Auto, do not render it 
     unbound_field.kwargs.setdefault('id', _Auto) 
     return super().bind_field(form, unbound_field, options) 

    def render_field(self, field, render_kw): 
     if field.id is _Auto: 
      field.id = False 
     return super().render_field(field, render_kw) 

class MyForm(flask_wtf.Form): 
    Meta = NoIdAttributeMeta 

或務實:

你也可以添加不同的前綴爲您的表單的每個實例,因此你必須唯一ID:

my_form = MyForm(prefix="form1") 
    pass 
1

我想你可以通過自定義ID到外地的構造是這樣的:

<form> 
    {{ form.name(id_='yourId') }} 
</form> 
... 
<form> 
    {{ form.name(id_='yourId2') }} 
</form> 
1

您不需要id = False,因爲您在調用render_field()時已經可以設置id()

{% macro render_field(_field) %} 
<label> 
    <span>{{ _field.label.text }} </span> 
    {{ _field(**kwargs) }} 
</label> 
{% endmacro %} 

用法:

{{ render_field(field, id=False) }} 

釋: 因爲你**** kwargs **,你可以使ID =假,這將是更dymanic。您可以選擇何時刪除身份證。 希望幫助那些使用Google解決方案的人

相關問題