Show BooleanField checkbox before label

守給你的承諾、 提交于 2019-12-20 04:16:48

问题


I'm in the process of trying to minimize the amount of code I need to use to render a form with bootstrap styling with the hope of rendering with just {{ form }} but I haven't yet managed to find a way to render a BooleanField with the checkbox before the text.

from django.forms import Form, BooleanField
class MyForm(Form):
     field = BooleanField(label='Test Label')
MyForm().as_table()

The above test code will output

<tr><th><label for="id_field">Test Label:</label></th><td><input class="" id="id_field" name="field" type="checkbox" /></td></tr>

But what I'm hoping to achieve is the same look and feel as shown in the bootstrap docs.

<label for="id_field"><input class="" id="id_field" name="field" type="checkbox" />Test Label:</label>

The problem in doing this is that the rendering is handled via the form, where the label and the field are positioned/rendered separately, and I have yet to find a place to override that will allow me to render the widget inside of the label...

Any ideas how I can achieve this?

I don't want to use django-bootstrap3 etc, and I've looked through the source code for them too and cant see anywhere where they've managed to achieve this either.


回答1:


It turns out this is much more intrinsic to do than it would appear to be and involves providing a form field mixin as well as a custom widget.

All too much work for me to maintain.

However!

django-angular has managed to achieve this with their own CheckboxInput and associated BooleanFieldMixin, since this is something I am planning on using, it has resolved my issue.



来源:https://stackoverflow.com/questions/34747964/show-booleanfield-checkbox-before-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!