Django Crispy Forms and Bootstrap Awesome Checkbox

2019-05-29 02:10发布

问题:

Is there any way to get Django Crispy-forms to emit the layout for a checkbox in a slightly different way to accomodate Bootstrap Awesome Checkbox (https://github.com/flatlogic/awesome-bootstrap-checkbox)?

NOTE: this can't be done via a CSS change. The INPUT tag is no longer a child of the LABEL tag with the awesome-checkbox...it's a sibling at the same level as the LABEL tag. Crispy Forms renders like this:

<div class="checkbox">
  <label>
    <input type="checkbox"> Check me out
  </label>
</div>

but awesome-checkbox needs to render like this:

<div class="checkbox">
   <input type="checkbox" id="checkbox1">
   <label for="checkbox1">
       Check me out
   </label>
</div>

回答1:

There are many ways to implement this:

  1. You can simply add css to your model field (like here https://stackoverflow.com/a/18029091/3033586 )
  2. css_class kwarg (look here http://django-crispy-forms.readthedocs.org/en/d-0/layouts.html?highlight=css_class )

Field('your_boolean_field', css_class='checkbox-primary'),

  1. Also you can always override templates. Create your own template for field.html.

Field('your_boolean_field', template='some_path/boolean_field.html'),

where 'boolean_field.html' is your version of

python2.7/site-packages/crispy_forms/templates/bootstrap3/field.html

For example my date_field.html

{% load crispy_forms_field %}


<div id="div_{{ field.auto_id }}" class="form-group{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} has-error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
{% if field.label and form_show_labels %}
    <label for="{{ field.id_for_label }}" class="control-label {{ label_class }}{% if field.field.required %} requiredField{% endif %}">
        {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
    </label>
{% endif %}

<div class="controls {{ field_class }} input-group date">
    {% crispy_field field %}
    <span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
{% include 'bootstrap3/layout/help_text_and_errors.html' %}