简体   繁体   中英

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: 在此处输入图像描述

what I get: 在此处输入图像描述

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 theBootstrap 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.

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"),
)

I managed to achieve this by using HTML blocks in the helper.

在此处输入图像描述

form.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(
            HTML('<label class="form-check-label" for="on_prem">On Prem</label>'),
            HTML('<div class="form-switch">'),
            Field('on_prem'),
            HTML('</div>'),css_class='col-md-3',),
            css_class='row',
        ),
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM