Django: How to pre-populate FormView with dynamic (non-model) data?

Question:

I have a FormView view, with some additional GET context supplied using get_context_data():

class SignUpView(FormView):
    template_name = 'pages_fixed/accounts/signup.html'
    form_class = SignUpForm

    def get_context_data(self, **kwargs):
        context = super(SignUpView, self).get_context_data(**kwargs)
        context = {
            'plans':    common.plans,
            'pricing':  common.pricing,
        }
        return context

This works fine. However, I also have some values in session (not from any bound model) which I would like to pre-populate into the form. These vary depending on user’s actions on previous page(s). I know (from my other post) that I can pass the form into the context (with initial=) but is it possible in a FormView situation per above?

Asked By: pete

||

Answers:

You can override the FormView class’s ‘get_initial’ method. See here for more info,

e.g.

def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    initial = super().get_initial()

    initial['my_form_field1'] = self.request.something

    return initial

‘get_initial’ should return a dictionary where the keys are the names of the fields on the form and the values are the initial values to use when showing the form to the user.

Answered By: user772401
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.