更新时间:2023-11-14 16:50:16
如果您想覆盖一般表单域的小部件,***的方法是设置 widgets
属性>ModelForm Meta 类:
If you want to override the widget for a formfield in general, the best way is to set the widgets
attribute of the ModelForm Meta
class:
要为字段指定自定义小部件,请使用内部 Meta 类的小部件属性.这应该是一个将字段名称映射到小部件类或实例的字典.
To specify a custom widget for a field, use the widgets attribute of the inner Meta class. This should be a dictionary mapping field names to widget classes or instances.
例如,如果您希望 Author 的 name 属性的 CharField 由 表示,而不是其默认的
,您可以覆盖该字段的小部件:
For example, if you want the a CharField for the name attribute of Author to be represented by a <textarea>
instead of its default <input type="text">
, you can override the field’s widget:
from django.forms import ModelForm, Textarea
from myapp.models import Author
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ('name', 'title', 'birth_date')
widgets = {
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
}
小部件字典接受小部件实例(例如,Textarea(...))或类(例如,Textarea).
The widgets dictionary accepts either widget instances (e.g., Textarea(...)) or classes (e.g., Textarea).
https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#overriding-the-default-fields