0

I have a form which I build dynamically based on data provided by the user using crispy-forms. For certain types of data, I want to provide a SplitDateTimeField to the user. I wanted to add attributes to this field, like a placeholder, a label or a help_text, but couldn't find any hint on how to do it.

Maybe I'm searching in the wrong place, but I couldn't find even a little piece of advice anywhere even though I've been searching for quite a while.

I used an AdminSplitDateTime widget in order to at least get labels :

datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime())

While it gets closer to what I want, that's not exactly it. I've searched in the documentation and tried with a SplitDateTimeWidget but didn't manage to make any of its attributes to work.

I'm currently lost as to what I should do so I'm asking here.

My form, simplified (I kept the crispy FormHelper in it in case it impacts the behaviour of the form) :

from crispy_forms.helper import FormHelper
from django.urls import reverse_lazy

class ScriptInputForm2(forms.Form):
    datetime = forms.SplitDateTimeField(widget=AdminSplitDateTime())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        self.helper = FormHelper()

        self.helper.add_input(Submit('submit', 'Submit'))
        self.helper.add_input(Submit('cancel', 'Back To Selection Page', css_class='ms-2 btn btn-danger'))

        self.helper.attrs = {
            'novalidate': ''
        }

        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-2'
        self.helper.field_class = 'col-10'
        
        self.helper.form_action = reverse_lazy('index')
Balizok
  • 904
  • 2
  • 5
  • 19

1 Answers1

1

I ended up using a DateTimeField with a DateTimeInput widget of type datetime-local :

class ScriptInputForm2(forms.Form):
    datetime = forms.DateTimeField(
        widget=forms.DateTimeInput(
            attrs={
                'step': 1, 
                'placeholder': 'My datetime field',
                'onfocus': "(this.type='datetime-local')",
                'onblur': "(this.type='text')",
            }
        )
    ),

The step attribute is useful in order to get the seconds to be displayed, whereas the onfocus and onblur ones allow the display of the placeholder while the field is empty and not on focus.

Balizok
  • 904
  • 2
  • 5
  • 19