Femme Fatale
Femme Fatale

Reputation: 880

How to use widgets in Django Crisp Forms

I am using Django Crispy forms and its FormHelper. In my FormHelper class i want that one of the field should use widgets. The reason for using widget is that i want to populate a date picker in one of the field.

Using the Field, i am able to populate the DatePicker in my updated_date by identifying the css_class. But i want to give DatePicker a format and theme (attrs). How will i be able to do that?

forms.py

class DeviceFilterFormHelper(FormHelper):
    # form_class = "form form-inline"

    form_id = "Device-search-form"
    form_method = "GET"
    form_tag = True
    html5_required = True
    layout = Layout(
        Div(
            Div('name', css_class="col-md-6"),
            Div('location', css_class="col-md-6"),
            css_class='row'
        ),
        Div(
            Div('phone_number', css_class="col-md-6"),
            Div(Field('updated_date', css_class="date-time-picker")),
            css_class='row'
            ),
        FormActions(
            Submit("submit", ("Search"), css_class="col-md-5"),
            css_class="col-8  text-right align-self-center",
        ),
    )

Below is the widget along with its attributes which i want to use in the FormHelper.

updated_date = forms.DateInput(attrs={
                                               'required': True,
                                               'class': 'date-time-picker',
                                               'data-options': '{"format":"Y-m-d H:i", "timepicker":"true"}'

                                           }),

I just can't figure out how will i be using the widget.

Upvotes: 0

Views: 2970

Answers (1)

YellowShark
YellowShark

Reputation: 2269

I don't believe you can do this in your FormHelper-based class, instead what I usually do is to hook into the __init__ method of the form class, and that's where I'll perform any alterations to the form/layout/widgets, etc. Something along these lines might work for you:

class DeviceFilterFormHelper(FormHelper):
    ... # no changes to your class/code from above


class DeviceFilterForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(DeviceFilterForm, self).__init__(*args, **kwargs)
        self.helper = DeviceFilterFormHelper(self)
        self.fields['updated_date'].widget = forms.DateInput(attrs={
                'required': True,
                'class': 'date-time-picker',
                'data-options': '{"format":"Y-m-d H:i", "timepicker":"true"}'
            })

Note that this technique isn't tied to Crispy - you can do this with any Django form, whether you're using Crispy to render it or not.

Upvotes: 0

Related Questions