Python Django:如何使用动态(非模型)数据预填充 FormView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22083218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:12:27  来源:igfitidea点击:

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

pythondjangodjango-templates

提问by pete

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

我有一个 FormView 视图,使用 get_context_data() 提供了一些额外的 GET 上下文:

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?

这工作正常。但是,我在会话中也有一些值(不是来自任何绑定模型),我想将它们预填充到表单中。这些因用户在前一页上的操作而异。我知道(从我的另一篇文章中)我可以将表单传递到上下文中(with initial=)但是在上面的 FormView 情况下是否可能?

采纳答案by user772401

You can override the FormView class's 'get_initial' method. See herefor more info,

您可以覆盖 FormView 类的“get_initial”方法。请参阅此处了解更多信息,

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.

'get_initial' 应该返回一个字典,其中键是表单上字段的名称,值是向用户显示表单时使用的初始值。