本文介绍了在基于类的通用视图中将初始值设置为modelform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用基于Class的通用视图,有人可以建议我如何设置初始值以更新表单?我尝试使用get_initial()方法,没有成功。以下是我尝试的代码
类IncidentUpdateView(UpdateView):
form_class = IncidentForm
form_class。初始= {badge_number:'88888'}
model =事件
template_name ='hse /事件/事件_update.html'
def get_initial(self,form_class) b $ b 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
方法,该方法返回包含初始值的字典:
class IncidentUpdateView(UpdateView):
def get_initial(self):
return {'value1' foo','value2':'bar'}
或者,您可以定义一个初始
值:
class IncidentUpdateView(UpdateView):
initial = {'value1':'foo','value2':'bar'}
I'm using Class based generic views, can anybody suggest me how can i set the initial values to update form?
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])
解决方案
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' }
Alternatively, you can define an initial
value:
class IncidentUpdateView(UpdateView):
initial = { 'value1': 'foo', 'value2': 'bar' }
这篇关于在基于类的通用视图中将初始值设置为modelform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!