我正在尝试在模型字段中指定字符长度。我无法将其呈现在页面上,也无法将size属性放到输入字段中。
基本形式如下:
class QuestionForm(ModelForm):
question = forms.CharField(label="Question")
class Meta:
model = Question
fields = ["question"]
我尝试了以下方法:
class QuestionForm(ModelForm):
question = forms.CharField(label="Question",widgets=forms.TextInput(attrs={'size':'50'}))
class Meta:
model = Question
fields = ["question"]
和
class QuestionForm(ModelForm):
question = forms.CharField(label="Question")
class Meta:
model = Question
fields = ["question"]
widgets = {
'question': forms.TextInput(attrs={'size':'50'})
}
和
类QuestionForm(ModelForm): 问题= Forms.CharField(label =“问题”)
def __init__(self, *args, **kwargs):
super(QuestionForm,self).__init__(*args, **kwargs)
self.fields['question'].widget.attrs['size'] = '50'
该表单是表单集工厂的一部分,使用该表单时您需要做其他不同的事情吗?
ApplicationForm = forms.formset_factory(QuestionForm)
ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',))
答案 0 :(得分:0)
问题是因为使用modelformset_factory时,我传递的是问题模型而不是表单,所以根本不使用form类。我设法找到了将小部件传递给modelformset_factory的解决方案。
ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',),widgets={"question": forms.TextInput(attrs={'size':'50'})})