Django forms.DateInput does not apply the attributes specified in the attrs field

Placeholder, the class is not set when they tried to apply it through the django attrs specifier for forms.DateInput

ModelForm Form.

And according to docs

Accepts the same arguments as TextInput, with another optional argument:

Here is the code:

widgets = { 'my_date_field': forms.DateInput(format=('%d-%m-%Y'), attrs={'class':'myDateClass', 'placeholder':'Select a date'} ) } 

The same applies for forms.TextInput , and it works fine.

What am I missing here?

Someone just needs the full class code:

 class trademark_form(ModelForm): my_date_field = DateField(input_formats=['%d-%m-%Y']) class Meta: model = myModel widgets = { 'my_date_field': forms.DateInput(format=('%d-%m-%Y'), attrs={'class':'myDateClass', 'placeholder':'Select a date'}), 'field1': forms.TextInput(attrs={'class':'textInputClass', 'placeholder':'Enter a Value..'}), 'field2': forms.TextInput(attrs={'class':'textInputClass', 'placeholder':'Enter a Value..', 'readonly':'readonly', 'value':10}), 'desc': forms.Textarea(attrs={'class':'textAreaInputClass', 'placeholder':'Enter desc', 'rows':5}), } exclude = ('my_valid_field') 

The generated HTML for the field, my_date_field :

 <input type="text" id="id_my_date_field" name="my_date_field"> 

The generated HTML for the field, field1 :

 <input type="text" name="field1" class="textInputClass" placeholder="Enter a Value.." id="id_field1"> 
+6
source share
2 answers

Since you did not publish your form code, I think you explicitly created an instance of the form field, such as , confirmed my hypothesis by posting code that looks something like this:

 class MyForm(forms.ModelForm): my_date_field = forms.DateField() class Meta: model = MyModel widgets = { 'my_date_field': forms.DateInput(format=('%d-%m-%Y'), attrs={'class':'myDateClass', 'placeholder':'Select a date'}) } 

I can say that it does not work, because if you explicitly create a form field like this, Django assumes that you want to fully define the behavior of the form field; therefore, you cannot use the widgets attribute of the Meta inner class.

A note at the end of the section on overriding default field types or widgets states that:

Fields defined declaratively remain as-is, so any settings made for Meta attributes such as widgets, labels, help_texts or error_messages are ignored; they apply only to fields that are automatically generated.

+11
source

based on @Martin's answer and reading Django documentation the final solution should be:

 class MyForm(forms.ModelForm): my_date_field = forms.DateField( widget=forms.DateInput(format=('%d-%m-%Y'), attrs={'class':'myDateClass', 'placeholder':'Select a date'})) class Meta: model = MyModel widgets = { } 
+2
source

All Articles