0

I would like to generate an "update formset" to update a large number of instances in one go, where the updated field is empty in the database (at the time of rendering the update formset) but is "suggested" using an already filled-in field.

My model goes here:

class Event(models.Model):
    plan_start_time = models.TimeField()
    actual_start_time = models.TimeField(blank=True, null=True)

So what I'd like is a table where actual_start_time is suggesting plan_start_time as pre-filled (initial) value.

What I tried:

class EventForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args, **kwargs)
        self.fields['actual_start_time'].initial = self.fields['plan_start_time']  # doesn't work 
        self.fields['actual_start_time'].initial = "08:00" # doesn't work either
        self.fields['actual_start_time'].initial = datetime.time(hour=8)  # doesn't work...
        self.initial['actual_start_time'] = self.fields['plan_start_time'] # this puts '<django.forms.fields.TimeField object at 0x067BA330>' in the field... not its value

    class Meta:
        model = Event
        fields = ('plan_start_time', 'actual_start_time', )

# Specifying form to use
MyFormSet = modelformset_factory(Event, extra=0, fields=('plan_start_time', 'actual_start_time'), form=EventForm)

I guess the question comes down to: can I access a form field value in the __init__() of the form? If not, what would be a workaround for this issue?

As an alternative, I'm looking into rendering plan_start_time as a hidden field and then copying it over to the actual_start_time fields for every field in my table, using Javascript. But I'd be surprised if there would be no Django client side way to do this, so would like to avoid JS for now.

Using Django 1.8.

SaeX
  • 17,240
  • 16
  • 77
  • 97
  • http://stackoverflow.com/questions/1897756/different-initial-data-for-each-form-in-a-django-formset – Shang Wang Nov 05 '15 at 14:54
  • Thanks @ShangWang, I had a look at that one, but it doesn't seem to cover my use case. I want to pre-fill data dependent on another field. Furthermore I'm wondering why the above doesn't work. – SaeX Nov 05 '15 at 15:04

1 Answers1

0

This can be done by providing a form to use in the modelformset_factory and overriding __init__() the proper way. Using self.instance, the object's existing form value can be accessed:

def __init__(self, *args, **kwargs):
    super(EventForm, self).__init__(*args, **kwargs)
    if not self.instance.actual_start_time:
        self.initial['actual_start_time'] = self.instance.plan_start_time
SaeX
  • 17,240
  • 16
  • 77
  • 97