使用Django Crispy Forms渲染单独的MultiWidget字段 [英] Rendering separate MultiWidget fields using Django Crispy Forms
问题描述
我的具体情况是,我需要将此字段显示为一行(使用Bootstrap 3):
My specific case is that I need this field rendered in one line (using Bootstrap 3):
所以像这样:
<div class="form-group">
<label>Amount:</label>
<div class="row">
<input name="amount_0" type="number" class="col-xs-8">
<select name="amount_1" class="col-xs-4">...</select>
</div>
</div>
使用: https://github.com/jakewins/django-money
窗口小部件: https://github.com/jakewins/django-money/blob/master/djmoney/forms/widgets.py
型号:
from djmoney.models.fields import MoneyField
class MyModel(models.Model):
...
amount = MoneyField(...)
...
表格:
class MyForm(forms.ModelForm):
...
@property
def helper(self):
helper = FormHelper()
helper.form_tag = False
helper.layout = Layout()
helper.layout.fields = [
...
'amount',
...
]
return helper
...
推荐答案
django-crispy-forms 无法处理字段小部件的呈现, django 可以处理.与 django.forms.MultiWidget
相同.
django-crispy-forms 不会分别渲染MultiWidget中的每个字段.
django-crispy-forms does not handle the rendering of the field widget, django handles that. It is the same with django.forms.MultiWidget
.
django-crispy-forms does not render each field from the MultiWidget separately.
请参阅: django.form.MultiWidget.format_output(rendered_widgets)
from djmoney.forms.widgets import MoneyWidget
class CustomMoneyWidget(MoneyWidget):
def format_output(self, rendered_widgets):
return ('<div class="row">'
'<div class="col-xs-6 col-sm-10">%s</div>'
'<div class="col-xs-6 col-sm-2">%s</div>'
'</div>') % tuple(rendered_widgets)
class BookingForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
super(BookingForm, self).__init__(*args, **kwargs)
amount, currency = self.fields['amount'].fields
self.fields['amount'].widget = CustomMoneyWidget(
amount_widget=amount.widget, currency_widget=currency.widget)
...
对于Django 1.11 +:
由于 更改
,则需要使用 新模板api
.相反,您的自定义资金小部件应如下所示:
For Django 1.11+:
Due to a change
, you need to use the new template api
. Instead, your custom money widget should look like:
class CustomMoneyWidget(MoneyWidget):
template_name = 'widgets/money.html'
使用模板money.html
With template money.html
<div class="row">
<div class="col-xs-6 col-sm-10">
{% with widget=widget.subwidgets.0 %}
{% include widget.template_name %}
{% endwith %}
</div>
<div class="col-xs-6 col-sm-2">
{% with widget=widget.subwidgets.1 %}
{% include widget.template_name %}
{% endwith %}
</div>
</div>
这篇关于使用Django Crispy Forms渲染单独的MultiWidget字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!