Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering separate MultiWidget fields using Django Crispy Forms

My specific case is that I need this field rendered in one line (using Bootstrap 3):

enter image description here

So something like:

<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>

Using: https://github.com/jakewins/django-money
Widget: https://github.com/jakewins/django-money/blob/master/djmoney/forms/widgets.py

Model:

from djmoney.models.fields import MoneyField

class MyModel(models.Model):
    ...
    amount = MoneyField(...)
    ...

Form:

class MyForm(forms.ModelForm):
    ...
    @property
    def helper(self):
        helper = FormHelper()
        helper.form_tag = False

        helper.layout = Layout()
        helper.layout.fields = [
            ...
            'amount',
            ...
        ]

        return helper
    ...
like image 533
demux Avatar asked Oct 12 '14 23:10

demux


1 Answers

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.

See: django.forms.MultiWidget.format_output(rendered_widgets)

This is how to render a MultiWidget to twitter-bootstrap-3 columns In 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)
    ...

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'

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>
like image 57
demux Avatar answered Nov 10 '22 12:11

demux