本文介绍了在基于类的通用视图中将初始值设置为 modelform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用基于类的通用视图,有人可以建议我如何设置初始值以更新表单吗?
I'm using Class based generic views, can anybody suggest me how can i set the initial values to update form?
我尝试使用 get_initial() 方法,但没有成功.以下是我试过的代码
I tried using get_initial() method but didn't got any success. Following is the code which i tried
class IncidentUpdateView(UpdateView):
form_class = IncidentForm
form_class.initial = {"badge_number": '88888'}
model = Incident
template_name = 'hse/incident/incident_update.html'
def get_initial(self, form_class):
initials = {
"badge_number": '88888'
}
form = form_class(initial=initials)
return form
def get_success_url(self):
return reverse_lazy('hse-incident', args=[self.object.id])
推荐答案
你应该定义一个 get_initial
方法,它返回一个包含初始值的字典:
You should define a get_initial
method which returns a dictionary that contains the initial values:
class IncidentUpdateView(UpdateView):
def get_initial(self):
return { 'value1': 'foo', 'value2': 'bar' }
或者,您可以定义一个 initial
值:
Alternatively, you can define an initial
value:
class IncidentUpdateView(UpdateView):
initial = { 'value1': 'foo', 'value2': 'bar' }
这篇关于在基于类的通用视图中将初始值设置为 modelform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!