Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...