使用django crispy表单为表单集提供自定义ID

使用django crispy表单为表单集提供自定义ID,django,django-crispy-forms,Django,Django Crispy Forms,我想给一个DIV一个自定义id,它使用一个表单集提供一个清晰的表单。 我试图在表单布局中使用forloop.counter,因为它说它将被注入模板呈现中,但它不起作用,它只是被呈现为css\u id='liveprice{{{forloop.counter}} class PrinterMaterialForm(ModelForm): class Meta: model = PrinterMaterial fields = ('material', 'ho

我想给一个DIV一个自定义id,它使用一个表单集提供一个清晰的表单。 我试图在表单布局中使用forloop.counter,因为它说它将被注入模板呈现中,但它不起作用,它只是被呈现为css\u id='liveprice{{{forloop.counter}}

class PrinterMaterialForm(ModelForm):
    class Meta:
        model = PrinterMaterial
        fields = ('material', 'hour_cost', 'gram_cost', 'colors')

    def __init__(self, *args, **kwargs):
        super(PrinterMaterialForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.form_class = 'form-inline'
        self.helper.field_template = 'bootstrap3/layout/inline_field.html'
        self.helper.disable_csrf = True
        self.helper.layout = Layout(
            Div(
                Div(
                    Div(css_class='col-md-4', css_id='liveprice_{{ forloop.counter }}'),
                    css_class='row',
                ),
            ),
        )
我找到了解决办法。 实际上,django crispy forms足够聪明,可以在注入的上下文中模拟{{forloop}}

问题是,它只呈现字段、HTML等节点,而不呈现css_类、css_id属性

因此,我使用的解决方案如下:

self.helper.layout = Layout(
    Div(
        Div(
            HTML("<div class='col-md-4' id='liveprice_{{ forloop.counter }}'></div>"),,
            css_class='row',
        ),
    ),
)
我希望它能帮助别人