设置初始值基于类的通用视图的ModelForm(Set initial value to model

2019-06-25 13:49发布

我使用基于类的通用视图,可以有人建议我怎么可以设置初始值更新形式?

我试着用get_initial()方法,但并未有任何的成功。 以下是我试过的代码

  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])

Answer 1:

您应该定义一个get_initial它返回一个包含初始值的字典方法:

class IncidentUpdateView(UpdateView):

    def get_initial(self):
        return { 'value1': 'foo', 'value2': 'bar' }

或者,你可以定义一个initial值:

class IncidentUpdateView(UpdateView):
    initial = { 'value1': 'foo', 'value2': 'bar' }


文章来源: Set initial value to modelform in class based generic views