0

I am trying to specify the length in characters on a model field. I cannot get it to render on the page and drop in the size attribute to the input field.

The basic form looks like:

class QuestionForm(ModelForm):
question = forms.CharField(label="Question")

class Meta:
    model = Question
    fields = ["question"]

I have tried the following:

class QuestionForm(ModelForm):
question = forms.CharField(label="Question",widgets=forms.TextInput(attrs={'size':'50'}))

class Meta:
    model = Question
    fields = ["question"]

And

class QuestionForm(ModelForm):
question = forms.CharField(label="Question")

class Meta:
    model = Question
    fields = ["question"]
    widgets = {
        'question': forms.TextInput(attrs={'size':'50'})
    }

And

class QuestionForm(ModelForm): question = forms.CharField(label="Question")

def __init__(self, *args, **kwargs):
    super(QuestionForm,self).__init__(*args, **kwargs)
    self.fields['question'].widget.attrs['size'] = '50'

The form is part of a formset factory, do you need to do anything different when using that?

ApplicationForm = forms.formset_factory(QuestionForm)
ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',))
4

1 回答 1

0

问题是因为在使用 modelformset_factory 时,我传入的是问题模型而不是表单,所以它根本没有使用表单类。我设法找到了将小部件传递给 modelformset_factory 的解决方案。

ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',),widgets={"question": forms.TextInput(attrs={'size':'50'})})
于 2019-11-02T16:20:16.793 回答