Pre-populate an inline FormSet?

后端 未结 10 1561
自闭症患者
自闭症患者 2020-11-30 18:25

I\'m working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here\'s the model

10条回答
  •  一生所求
    2020-11-30 19:03

    Django 1.4 and higher supports providing initial values.

    In terms of the original question, the following would work:

    class AttendanceFormSet(models.BaseInlineFormSet):
        def __init__(self, *args, **kwargs):
            super(AttendanceFormSet, self).__init__(*args, **kwargs)
            # Check that the data doesn't already exist
            if not kwargs['instance'].member_id_set.filter(# some criteria):
                initial = []
                initial.append({}) # Fill in with some data
                self.initial = initial
                # Make enough extra formsets to hold initial forms
                self.extra += len(initial)
    

    If you find that the forms are being populated but not being save then you may need to customize your model form. An easy way is to pass a tag in the initial data and look for it in the form init:

    class AttendanceForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(AttendanceForm, self).__init__(*args, **kwargs)
            # If the form was prepopulated from default data (and has the
            # appropriate tag set), then manually set the changed data
            # so later model saving code is activated when calling
            # has_changed().
            initial = kwargs.get('initial')
            if initial:
                self._changed_data = initial.copy()
    
        class Meta:
            model = Attendance
    

提交回复
热议问题