带有切换开关元件的Django脆皮形式
我正在使用脆皮形式和布局助手来生成我的输入形式。我想在表单中添加一个切换开关。
forms.py:models.py:form.html
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',
),
)
我在
class Request(models.Model):
on_prem = models.BooleanField(default=False)
i.sstatic.net/dom1j.png
<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>
中看到的。 com/doc/5.1/forms/checks radios/#switches“ rel =“ nofollow noreferrer”> bootstrap文档 nested css class Ins the Twoggle Switch效果我希望通过嵌套的CSS类实现,我不确定如何实现这一目标通过形式助手。任何帮助将不胜感激。
I am using Crispy Forms and layout helper to generate my Input form. I'd like to add a Toggle switch into the form.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅使用“字段”的代码行较少:
Fewer lines of code just using "Field":
如果使用django-crispy-forms
crispy-bootstrap5
使用bootstrap5模板包,则可以使用switch> switch> switch
输入类型:https://github.com/django-crispy-forms/crispy-bootstrap5?tab5?tab = readme-ov-file#whats-new
If using the Bootstrap5 template pack for django-crispy-forms
crispy-bootstrap5
you can use theSwitch
input type:Reference: https://github.com/django-crispy-forms/crispy-bootstrap5?tab=readme-ov-file#whats-new
我通过在助手中使用HTML块来实现这一目标。
form.py
I managed to achieve this by using HTML blocks in the helper.
form.py