gpt4 book ai didi

django - 使用 Django Crispy Forms 渲染单独的 MultiWidget 字段

转载 作者:行者123 更新时间:2023-12-02 02:36:52 27 4
gpt4 key购买 nike

我的具体情况是,我需要在一行中呈现此字段(使用 Bootstrap 3):

enter image description here

所以类似:

<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.forms.MultiWidget相同。
不会单独渲染 MultiWidget 中的每个字段。

参见:django.forms.MultiWidget.format_output(rendered_widgets)

这是如何将 MultiWidget 渲染到 Django 1.10-中的列:

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>

关于django - 使用 Django Crispy Forms 渲染单独的 MultiWidget 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26330965/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com