djangoformsformset

How to populate FormView with initial data?


While reading Django's documentation, I am trying to practice at the same time. Today I am reading Formsets; https://docs.djangoproject.com/en/4.0/topics/forms/formsets/

Now I am trying to populate generic FormView with initial data. Here is the code:

class ArticleFormView(FormView):
# same here, use FormSet instance, not standard Form
form_class = ArticleFormSet
template_name = 'article_form_view.html'
success_url = "/"

def get_initial(self):
    init_data = {'value1': 'foo', 'value2': 'bar'}
    return init_data

And this results a "in _construct_form defaults['initial'] = self.initial[i]
KeyError: 0"

So the question is how do I populate a formset in a FormView with initial data?


Solution

  • You need to pass initial data as a list where the i-th element is the initial data for the i-th form. So if you want to pass only initial data for the first form, you pass this as:

    class ArticleFormView(FormView):
        form_class = ArticleFormSet
        template_name = 'article_form_view.html'
        success_url = "/"
    
        def get_initial(self):
            return [{'value1': 'foo', 'value2': 'bar'}]  # 🖘 list of dictionaries

    If you want to pass it as initial data for all forms, you can use the form_kwargs parameter:

    class ArticleFormView(FormView):
        form_class = ArticleFormSet
        template_name = 'article_form_view.html'
        success_url = "/"
    
        def get_form_kwargs(self):
            data = super().get_form_kwargs()
            data['form_kwargs'] = {'initial': {'value1': 'foo', 'value2': 'bar'}}  # 🖘 initial for all forms
            return data