小编Lab*_*che的帖子

在表单字段中添加额外信息并在渲染django模板时使用它

我想为django表单的某些字段添加额外的信息,并在模板中使用它来添加一些额外的html标签

我有一个django形式,如:

class MyForm(forms.Form):
    integer = forms.IntegerField(
        help_text='Please enter your favorite integer number',
        label='Favorite integer',
        widget=forms.TextInput(attrs={'class':'input-xlarge'}))
    decimal = forms.DecimalField(
        min_value=Decimal('0.0001'),
        decimal_places=4,
        help_text='Please enter your favorite decimal number',
        label='Favorite decimal',
        widget=forms.TextInput(attrs={'class':'input-xlarge'}))
    ==> here I would like to say: decimal will have a new property
Run Code Online (Sandbox Code Playgroud)

我在模板中渲染MyForm,在每个字段上使用循环:

{% for item in form.visible_fields %}
  ==> here I would like to test if item has that property to add some html tags
  {{ item }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

我无法使用小部件的attrs,因为我想在渲染的输入标记之外使用属性信息.

我应该创建一个自定义字段,为我使用的所有字段编写自定义渲染器,还是有一个我错过的更简单的解决方案?


编辑:到目前为止,我的解决方案是:(简化版)主模板:

<form action="/somewhere/" …
Run Code Online (Sandbox Code Playgroud)

python forms django django-templates twitter-bootstrap

3
推荐指数
1
解决办法
5093
查看次数