django-crispy-forms - 默认类

时间:2014-05-06 07:10:05

标签: django django-forms django-crispy-forms

我正在尝试在现有项目中使用带有django-crispy-forms的Bootstrap包。

我有~15种形式,我希望有这些课程:

label_class = 'col-sm-3'
input_class = 'col-sm-9'

有没有办法在设置或其他地方指定这些默认值而无需更新我的所有表单?


另外,我以前使用的是django-bootstrap-form,我从模板中指定了类:

{{ my_form|bootstrap_horizontal:'col-sm-3' }}

我发现从模板而不是从表单定义控制渲染更合乎逻辑。表单可以在多个页面中使用,而不具有相同的呈现

2 个答案:

答案 0 :(得分:2)

不确定它非常漂亮,但我还没有找到任何更简单的解决方案,所以这就是我所做的:

由于我想避免更新所有表单,我将定义一个独立的帮助程序。

<强> my_helpers.py

from crispy_forms.helper import FormHelper

class MyColFormHelper(FormHelper):
    label_class = 'col-sm-3'
    field_class = 'col-sm-9'
    form_tag = False
    disable_csrf = True

由于我不想更新我的所有观点,因此我定义了一个注入帮助程序的上下文处理器

<强> my_context_processors.py

from my_app.my_helpers import *

def form_helpers(request):
    return {
        'col_form': MyColFormHelper()
    }

现在我可以直接从模板中指定帮助器

<form action="my_action" method="my_method">{% csrf_token %}
    {% crispy my_form col_form %}
</form>

这也允许我在不同的位置和布局中使用相同的表格。

这并没有完全回答问题&#34;默认类&#34;但是我帮助部署了助手。

我不喜欢的事情是,即使我们不需要帮助者,也会注射帮助者。
所以随时建议任何改进。

答案 1 :(得分:1)

Django-crispy-forms还为Bootstrap 3水平表单提供了一个选项:http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.html#bootstrap3-horizontal-forms

您只需要将3个属性(form_classlabel_classfield_class)添加到表单助手中,而不是将它们添加到每个表单字段中:

helper.form_class = 'form-horizontal'
helper.label_class = 'col-lg-2'
helper.field_class = 'col-lg-8'
helper.layout = Layout(
    'email',
    'password',
    'remember_me',
    StrictButton('Sign in', css_class='btn-default'),
)

来自docs:

  

在Bootstrap版本3中执行水平表单的方法是设置一些   标签和div包装字段中的col-lg-X类。这意味着一个   很多麻烦更新你的布局对象设置这些类,   太多的冗长。 而是添加了一些FormHelper属性   帮助您轻松实现这一目标。您只需要设置三个属性。

更新:适用于多种表单

对于多种形式,我这样做:

from crispy_forms.helper import FormHelper


def horizontal_helper(form):
    """ Adds the horizontal form classes
    to the given form"""
    form.helper = FormHelper(form)
    form.helper.form_class = 'form-horizontal'
    form.helper.label_class = 'col-md-2'
    form.helper.field_class = 'col-md-6'


class SomeForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        horizontal_helper(self)
        ...


class AnotherForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AnotherForm, self).__init__(*args, **kwargs)
        horizontal_helper(self)
        ...