[Answer]-How can I add extra textarea fields to a form

1👍

It’s hard to give you a good answer here because you haven’t indicated what you’re actually trying to achieve. You could add a 1000 text fields to your form, but if they don’t correlate somehow to data on your model, there’s not much point, and you’ve neglected that crucial piece of information.

Still, on a very basic level, you can add the additional textareas to your form like so:

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        for i in range(1, 11):
            self.fields['mytextarea%d' % i] = forms.CharField(label='Textarea %d' % i, widget=forms.Textarea)

UPDATE

Based on your comment, and the fact that you’re intending to actually store and retrieve the textarea fields at a later point, you should create a separate model for them and link it to your main model through a one-to-many relationship. For example:

class PrimaryModel(models.Model):
    ... # Stuff here

class TextareaModel(models.Model):
    myprimarymodel = models.ForeignKey(PrimaryModel)
    mytextarea = models.TextField()

It’s hard to give a good example since you haven’t indicated anything about what your models look like, but the basic idea is that you have a model that contains nothing but a foreign key to the main model and a textarea field. You can then treat these textareas as inlines with via a model formset.

Leave a comment