Django:如何使用动态(非模型)数据预先填充FormView? [英] Django: How to pre-populate FormView with dynamic (non-model) data?
问题描述
类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上下文
这工作正常。然而,我也有一些值,在会话(不是从任何约束的模型),我想预先填充的形式。这取决于用户在上一页的操作。我知道(从我的其他帖子),我可以将表单传递到上下文中(使用 initial =
),但是在上述的FormView情况下是否可能?
您可以覆盖FormView类的get_initial方法。有关更多信息,请参阅此处,
例如
def get_initial(self):
initial = super(SignUpView,self).get_initial()
初始['my_form_field1'] = self.request.something
返回初始
'get_initial'应该返回字典,其中键是表单上的字段的名称,值是在向用户显示表单时要使用的初始值。
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?
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(SignUpView, self).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.
这篇关于Django:如何使用动态(非模型)数据预先填充FormView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!