我试图在我的django表单中设置ChoiceField长度,我使用了以下内容:
from django.forms import TextInput, Textarea, ChoiceField
class SiteAdmin(admin.ModelAdmin):
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':'25'})},
models.ChoiceField: {'widget': TextInput(attrs={'size':'25'})},
models.GenericIPAddressField: {'widget': TextInput(attrs={'size':'25'})},
}
...
然后得到错误:
File "/var/www/infternal/sites/admin.py", line 18, in SiteAdmin
models.ChoiceField: {'widget': TextInput(attrs={'size':'25'})},
AttributeError: 'module' object has no attribute 'ChoiceField'
有谁知道我需要更改以更改选择/下拉长度?
由于
答案 0 :(得分:0)
因为您以错误的方式定义表单集。 ChoiceField是Django表单的属性,而不是Django模型。
您的代码应该是这样的:
SOME_CHOICES = (
('1', 'Choice1'),
('2', 'Choice2'),
)
class SiteAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TextInput(attrs={'size':'25'})},
models.CharField: {'widget': ChoiceField(choices=SOME_CHOICES,max_length=25})},
models.GenericIPAddressField: {'widget': TextInput(attrs={'size':'25'})},
}
答案 1 :(得分:0)
您可以覆盖formfield_for_foreignkey
或formfield_for_choicefield
以分别更改外键或选择字段的字段。例如:
def formfield_for_choice_field(self, db_field, request, **kwargs):
field = super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
field.widget.attrs['size'] = '25'
return field