How to add placeholder to forms.widgets.DateInput with attrs={'type': 'date',} in Django?

Viewed 965

I cannot add a placeholder to DateInput widget inside a form if I pass 'type': 'date' to attrs. However, if I don't pass 'type': 'date' to attrs the field behaves like a TextInput.

It looks super simple but I can't understand what's going wrong.

forms.py

class QueryClientsForm(forms.Form):
    initial_date = forms.DateField(
        widget=forms.widgets.DateInput(
            attrs={'placeholder': 'Initial date...', 'type': 'date', }))

query_clients.html

<div class="container h-50">
    <div class="row justify-content-center">
        <div class="register_card" style="display: inline-block;">
            <form method="POST" action="">
                {% csrf_token %}
                <div class="input-group">
                    {{form.initial_date}}
                    <input class="btn login_btn" type="submit" style="margin-left: 10;" value="SEARCH">
                </div>
            </form>
        </div>
    </div>
</div>

I tried to use some javascript aswell but it didn't work...

<script>

    var initial_date = document.getElementById('id_initial_date')

    initial_date.placeholder = 'Initial date...';
    
</script>

What I've to change?

2 Answers

I made it work adjusting the onfocus parameter and changing the type to text.

class QueryClientsForm(forms.Form):
    initial_date = forms.DateField(
        widget=forms.widgets.DateInput(
            attrs={'placeholder': 'Initial date...', 'type': 'text',
                   'onfocus': "(this.type='date')", }
        )
    )

when you pass attrs={'placeholder': 'Initial date...', 'type': 'date', } to a form field in gets rendered as <input type='date' placeholder='Initial date...'> but input field of type date in html5 does not support placeholder attribute. when you remove the type attribute it's rendered as type='text' which supports placeholder. if you want to show placeholder text you should look for jQuery library which has that support. Lastly if you want to show an initial date instead of default 'mm/dd/yyy' you can initialise like this

class QueryClientsForm(forms.Form):
    inital_date = forms.DateField(
        initial=datetime.now().strftime("%Y-%m-%d"),
        widget=forms.widgets.DateInput(
            attrs={'type': 'date'})
    )

UPDATE: If you use jQuery you can get the result using a workaround. Send id attribute instead of type in your form.

attrs={
    'placeholder': 'Initial date...',
    'id': 'date_field'
}

and in your template change type with jQuery.

<script>
    $(document).ready(function () {
        $("#date_field").focus(function () {
            $(this).prop('type', 'date');

        });

        $("#date_field").focusout(function () {
            $(this).prop('type', 'text');

        });

    });
</script>
Related