Django forms.DateInput 不应用 attrs 字段中给出的属性 [英] Django forms.DateInput does not apply the attributes given in attrs field
问题描述
占位符,尝试通过 django 的 attrs 说明符为 forms.DateInput
Placeholder, class not getting set when tried to apply through the django's attrs specifier for forms.DateInput
表单是一个 ModelForm.
并根据 docs
采用与 TextInput 相同的参数,但多了一个可选参数:
Takes same arguments as TextInput, with one more optional argument:
代码如下:
widgets = {
'my_date_field': forms.DateInput(format=('%d-%m-%Y'),
attrs={'class':'myDateClass',
'placeholder':'Select a date'}
)
}
同样适用于 forms.TextInput
并且它工作得很好.
The same is applied for a forms.TextInput
and it works just fine.
我在这里遗漏了什么?
任何人都想要完整的课程代码:
Just anybody wants a 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')
为字段生成的 HTML,my_date_field
:
The generated HTML for the field, my_date_field
:
<input type="text" id="id_my_date_field" name="my_date_field">
为字段生成的 HTML,field1
:
The generated HTML for the field, field1
:
<input type="text" name="field1" class="textInputClass" placeholder="Enter a Value.." id="id_field1">
推荐答案
由于你没有发布你的表单代码,我最好的猜测是你显式实例化了这样的表单字段 证实了我的猜测通过发布大致如下所示的代码:
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'})
}
我可以说这是行不通的,因为如果你像这样显式实例化一个表单域,Django 会假设你想要完全定义表单域行为;因此,您不能使用内部 Meta
类的 widgets
属性.
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.
关于覆盖默认字段类型或小部件指出:
声明性定义的字段保持原样,因此任何对 Meta 属性进行自定义,例如小部件、标签、help_texts 或 error_messages 被忽略;这些仅适用于领域自动生成.
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.
这篇关于Django forms.DateInput 不应用 attrs 字段中给出的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!