Different initial data for each form in a Django formset

Viewed 23706

Is it possible to prepopulate a formset with different data for each row? I'd like to put some information in hidden fields from a previous view.

According to the docs you can only set initial across the board.

5 Answers

I had this problem and I made a new widget:

from django.forms.widgets import Select
from django.utils.safestring import mark_safe
class PrepolutatedSelect(Select):
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = ''
        if value == '':
            value = int(name.split('-')[1])+1
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<select%s>' % flatatt(final_attrs)]
        options = self.render_options(choices, [value])
        if options:
            output.append(options)
        output.append('</select>')
        return mark_safe(u'\n'.join(output))

Maybe this will work for you too.

formset = BookFormset(request.GET or None,initial=[{'formfield1': x.modelfield_name1,'formfield2':x.modelfield_name2} for x in model])

formfield1,formfield2 are the names of the formfields.

modelfield_name1,modelfield_name2 are the modal field names.

model is name of your modal class in models.py file.

BookFormset is the form or formset name which is defined in your forms.py file

Related