Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

django - BooleanField checkbox not render correctly with crispy_forms using bootstrap

I am using crispy_forms and FormHelper. I have a model field declared as:

active = models.BooleanField(default=True)

And in my ModelForm, I have tried both the following in my Layout:

    self.helper.layout = Layout(
                    ...
        InlineCheckboxes('active'),
        Field('active'),
                    ...

which both not providing the desired result:

Please see image link

While using InlineCheckboxes, I do not see the checkbox and using only Field, it's not formatted correctly.

Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the link to the "Bootstrap Layout objects" section of Crispy Forms docs.

InlineCheckboxes: It renders a Django forms.MultipleChoiceField field using inline checkboxes

InlineCheckboxes isn't appropriate for your model's field-type.


A hacky way to achieve what you're looking for is to use PrependedText with an empty string for the text argument.

...
PrependedText('active', ''),
...

Examining the source it appears that a boolean field by default renders the <input> tag inside the <label> tag. Using the hack above, 'Active' stays in the <label> and the <input> is put where you'd expect: in a <div> with "control" css class. Compare the following:

PrependedText('active', ''):

  <div id="div_id_active" class="form-group">
    <label for="id_active" class="control-label">Active</label>

    <div class="controls">
      <div class="input-group">
        <input type="checkbox" name="active" class="checkboxinput" id="id_active" />
      </div>
    </div>
  </div>

Field('active'):

  <div class="form-group">
    <div id="div_id_active" class="checkbox">
      <div class="controls">
        <label for="id_active" class=""><input type="checkbox" name="active" class=
        "checkboxinput checkbox" id="id_active" /> Active</label>
      </div>
    </div>
  </div>

Update

I've confirmed that this is fixed in the dev branch of django-crispy-forms.

Reference this commit: 5c3a268

And this github issue: #267


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...