Django Crispy Form带有拨动开关元素

cfh9epnr  于 2022-11-26  发布在  Go
关注(0)|答案(2)|浏览(140)

我正在使用简易表单和布局帮助器生成输入表单。我想在表单中添加一个切换开关。
期望的结果:

我得到结果:

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>

我在Bootstrap文档中看到,我想要的切换开关效果是通过嵌套的css类实现的,我不知道如何通过窗体助手实现。任何帮助都将非常感谢。

bvjxkvbb

bvjxkvbb1#

仅使用“Field”的代码行更少:

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

mctunoxg2#

我设法通过在helper中使用HTML块来实现这一点。

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

相关问题