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

别等时光非礼了梦想. 提交于 2019-11-30 09:15:17

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.

based on response of @Martin and reading the 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 = {
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!