Set initial value to modelform in class based generic views

Asif picture Asif · Jun 19, 2012 · Viewed 16.5k times · Source

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

Answer

Simeon Visser picture Simeon Visser · Jun 19, 2012

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' }