【问题标题】:Django render a form field with css using crispy formsDjango 使用清晰的表单用 css 渲染表单字段
【发布时间】:2015-04-14 13:03:00
【问题描述】:

我有一个表格,我想用清晰的表格来渲染,

表格

class MyForm(forms.ModelForm):

    class Meta:
        model = MyModel
        excludes = ('user', 'created')

    def __init__(self, *args, **kwargs):


        self.helper = FormHelper()
        self.helper.form_show_labels = False ## I only need the input field
        self.helper.layout = layout.Layout(

            layout.Field('name', css_class="form-control"), 
            layout.Field('objective', css_class="form-control"),
            ## ADD CLASS form-control TO THE FIELDS (This is the problem since the fields are not rendered with the class)
        )
        super(MyForm, self).__init__(*args, **kwargs)

模板

<div class="form-group">
    <label>Name <i class="fa fa-question-circle tooltips" data-original-title="Lorem Ipsum" data-html="true" data-placement="right" data-container="body"></i></label>
    {{ form.name|as_crispy_field }}
    {{ form.name.errors|striptags }}
</div>
<div class="form-group">
    <label>Theme/ Objective <i class="fa fa-question-circle tooltips" data-original-title="Lorem Ipsum" data-html="true" data-placement="right" data-container="body"></i></label>
    {{ form.objective|as_crispy_field }}
    {{ form.objective.errors|striptags }}
</div>

字段不使用类form-control 呈现。 标签已呈现,我不需要它们,因为我有自定义标签。 任何有关如何使用类呈现字段的帮助将不胜感激。谢谢。

【问题讨论】:

  • 您可以考虑跳过crispy-forms 并手动呈现您的表单docs.djangoproject.com/en/1.7/topics/forms/…
  • @Selcuk。感谢您的建议,如何在字段中添加类表单控件?
  • 非常感谢。这似乎解决了我的问题。

标签: python django django-forms django-templates django-crispy-forms


【解决方案1】:

如果你手动渲染你的字段,你可以像这样添加它们:

<input type="text" name="{{ form.objective.html_name }}" 
       id={{ form.objective.id_for_label }}" 
       class="form-control">

请注意,这将要求您手动渲染所有 inputs。

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 1970-01-01
    • 2021-06-07
    • 2016-07-14
    • 1970-01-01
    • 2012-10-07
    • 2017-09-15
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多