Search code examples
djangodjango-formsdjango-crispy-formsdjango-bootstrap4

Django Crispy Form with Toggle switch element


I am using Crispy Forms and layout helper to generate my Input form. I'd like to add a Toggle switch into the form.

desired result: enter image description here

what I get: enter image description here

forms.py:

class RequestForm(forms.ModelForm):
on_prem = forms.CharField(widget=forms.CheckboxInput(attrs={"class": "slider form-control"}))

class Meta:
    model = Request
    fields = ['on_prem']

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.helper = FormHelper(self)
    self.helper.layout = Layout(
        Div(
            Div(Field('on_prem'), css_class='col-md-3', ),
            css_class='row',
        ),
    )

models.py:

class Request(models.Model):        
on_prem = models.BooleanField(default=False)

form.html

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {% crispy form %}
    <button type="submit" class="d-block btn mt-4 w-50 mx-auto">
        Save Request 
    </button>
</form>

I have seen in the Bootstrap documentation that the toggle switch effect I desire is achieved with nested css classes and I am not sure how to achieve that via the form helper. Any help would be greatly appreciated.


Solution

  • Fewer lines of code just using "Field":

    self.helper.layout = Layout(
        Field('notify_faculty_field', css_class="form-check-input", wrapper_class="form-check form-switch"),
    )