Home > Enterprise >  How to populate FormView with initial data?
How to populate FormView with initial data?

Time:01-02

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?

CodePudding user response:

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'}]  #            
  • Related