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

前端 未结 4 1827
情书的邮戳
情书的邮戳 2020-12-31 18:52

Placeholder, class not getting set when tried to apply through the django\'s attrs specifier for forms.DateInput

The form is a ModelForm.

And according to th

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 18:58

    Since you didn't post your form code, my best guess is that you explicitly instantiated a form field like this confirmed my guess by posting the code that looks roughly 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's not working because if you explicitly instantiate a form field like this, Django assumes that you want to completely define form field behavior; therefore, you can't use the widgets attribute of the inner Meta class.

    The note at the end of section about overriding the default field types or widgets states that:

    Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

提交回复
热议问题