【问题标题】:Set initial value to modelform in class based generic views在基于类的通用视图中将初始值设置为模型表单
【发布时间】:2012-06-21 05:39:15
【问题描述】:

我正在使用基于类的通用视图,谁能建议我如何设置初始值来更新表单?

我尝试使用 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])

【问题讨论】:

    标签: python django django-forms django-views django-class-based-views


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2011-12-23
      • 2013-12-03
      相关资源
      最近更新 更多