我的具体情况是我需要在一行中渲染这个字段(使用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不会单独渲染MultiWidget中的每个字段.
见:django.forms.MultiWidget.format_output(rendered_widgets)
这是如何在Django 1.10-中将MultiWidget呈现为twitter-bootstrap-3列:
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:
由于change
,您需要使用new template api
.相反,您的自定义资金小部件应如下所示:
class CustomMoneyWidget(MoneyWidget): template_name = 'widgets/money.html'
使用模板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>