Set initial value to modelform in class based generic views
Asked Answered
N

1

30

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])
Nichol answered 19/6, 2012 at 7:50 Comment(0)
C
56

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' }
Competitor answered 19/6, 2012 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.