Django:如何使用动态(非模型)数据预填充 FormView? [英] Django: How to pre-populate FormView with dynamic (non-model) data?
问题描述
我有一个 FormView 视图,使用 get_context_data() 提供了一些额外的 GET 上下文:
class SignUpView(FormView):template_name = 'pages_fixed/accounts/signup.html'form_class = 注册表格def get_context_data(self, **kwargs):context = super(SignUpView, self).get_context_data(**kwargs)上下文 = {'计划':common.plans,'定价':common.pricing,}返回上下文
这很好用.但是,我在会话中也有一些值(不是来自任何绑定模型),我想将它们预填充到表单中.这些因用户在前一页上的操作而异.我知道(从我的其他 post) 我可以将表单传递到上下文中(使用 initial=
)但是在上面的 FormView 情况下是否可能?
您可以覆盖 FormView 类的 'get_initial' 方法.请参阅此处了解更多信息,>
例如
def get_initial(self):"""返回用于此视图上的表单的初始数据."""初始 = super().get_initial()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().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屋!