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',))
OptimusPrime
  • 777
  • 16
  • 25
  • How are you displaying this field in the template? And what do you actually see? Also show the rest of the view; I can't see how those two formsets related to each other. – Daniel Roseman Nov 02 '19 at 12:38
  • Thanks, I have managed to find the solution, I will post it as an answer. – OptimusPrime Nov 02 '19 at 16:15

1 Answers1

0

The issue was because when using a modelformset_factory, I am passing in the question model not the form so it is not using the form class at all. I managed to find the solution which was to pass in the widgets to the modelformset_factory.

ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',),widgets={"question": forms.TextInput(attrs={'size':'50'})})
OptimusPrime
  • 777
  • 16
  • 25
  • Sorry, I have problems interpreting documentation sometimes due to learning difficulties. Please let me know if this is not of any help to anyone and I can delete the question. If it's still of use then I am happy to leave it on here. – OptimusPrime Nov 02 '19 at 16:20