[Answered ]-How to add a placeholder attribute in Django Form

2👍

It’s a bit late, but I’ll chip in anyway. I’ve been trying to do the same thing without having to redefine the widgets used in the form. Discovered that the following works:

class ExampleForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)

        # sets the placeholder key/value in the attrs for a widget
        # when the form is instantiated (so the widget already exists)
        self.fields['name_of_field'].widget.attrs['placeholder'] = 'random placeholder'

EDIT: although I realize this doesn’t answer your question of why your code doesn’t work…

0👍

in form itself, this works for me always

class SampleForm(ModelForm):
    class Meta:
        model = Sample

    name = forms.CharField(
        label='Name', 
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'placeholder': 'Enter title here'}
        )
    )

Leave a comment