Django: Store many forms into one table
<p>I'm using django v1.8.</p>

<p>A have one table split into four forms.</p>

<p>Example from my <code>views.py</code></p>

<pre><code>ext_cent = ExternalCentersForm(request.POST, prefix='extcent')
ext_cent_diagnostic = ExternalCentersDiagnosticForm(request.POST,prefix='extcentDiagn')
ext_cent_outcomes = ExternalCentersOutcomesForm(request.POST,prefix='extcentOutcomes')
ext_cent_outcomes2 = ExternalCentersOutcomes2Form(request.POST,prefix='extcentOutcomesTwo')
</code></pre>

<p>When I'm trying to save them I use </p>

<pre><code>ext_cent_object = ext_cent.save(commit=False)
ext_cent_object.author = request.user
ext_cent_object.save()
ext_cent_diagnostic_object = ext_cent_diagnostic.save(commit=False)
ext_cent_diagnostic_object.author = request.user
ext_cent_diagnostic_object.save()
ext_cent_outcomes_object = ext_cent_outcomes.save(commit=False)
ext_cent_outcomes_object.author = request.user
ext_cent_outcomes_object.save()
ext_cent_outcomes2_object = ext_cent_outcomes2.save(commit=False)
ext_cent_outcomes2_object.author = request.user
ext_cent_outcomes2_object.save()
</code></pre>

<p>My <code>forms.py</code>: </p>

<pre><code>class ExternalCentersForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExternalCentersForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        #self.fields['patient'].queryset = Demographic.objects.filter(patient_id=self.instance.patient)
        self.helper.field_class = 'col-md-8'
        self.helper.label_class = 'col-md-3'
        self.helper.layout = Layout(
            Fieldset(
                '&lt;b&gt;Center Information&lt;/b&gt;',
                Div(
                        #HTML(u'&lt;br/&gt;&lt;div class="col-md-9"&gt;&lt;h4&gt;&lt;b&gt;Molecular analysis&lt;/b&gt;&lt;/h4&gt;&lt;/div&gt;&lt;br/&gt;&lt;br/&gt;'),
                        Div('location_of_center',css_class='col-md-6'),
                        Div('name_of_center',css_class="col-md-6"),
                        Div('type_of_center',css_class="col-md-6"),
                        css_class='row',
                        ),

                ),


            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = Ext_centers
        exclude = ['center_id', 'author']
        list_display = ('title', 'pub_date', 'author')


class ExternalCentersDiagnosticForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExternalCentersDiagnosticForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        #self.fields['patient'].queryset = Demographic.objects.filter(patient_id=self.instance.patient)
        self.helper.field_class = 'col-md-8'
        self.helper.label_class = 'col-md-3'
        self.helper.layout = Layout(
            Fieldset(
                '&lt;b&gt;Diagnostic categories&lt;/b&gt;',
                Div(
                        HTML(u'&lt;div class="col-md-9"&gt;&lt;h4&gt;&lt;b&gt;Paroxysmal nocturnal haemoglobinuria (PNH)&lt;/b&gt;&lt;/h4&gt;&lt;/div&gt;'),
                        Div('diagn_categ_pnh_no_patient',css_class='col-md-6'),
                        Div('diagn_categ_pnh_distribution',css_class="col-md-6"),
                        css_class='row',
                        ),


                ),
            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = Ext_centers
        exclude = ['center_id', 'author']
        list_display = ('title', 'pub_date', 'author')

class ExternalCentersOutcomesForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExternalCentersOutcomesForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        #self.fields['patient'].queryset = Demographic.objects.filter(patient_id=self.instance.patient)
        self.helper.field_class = 'col-md-8'
        self.helper.label_class = 'col-md-3'
        self.helper.layout = Layout(
            Fieldset(
                '&lt;b&gt;1. Deaths&lt;/b&gt;',
                Div(
                        HTML(u'&lt;div class="col-md-9"&gt;&lt;h4&gt;&lt;b&gt;2015&lt;/b&gt;&lt;/h4&gt;&lt;/div&gt;'),
                        Div('outcomes_year2015_thal',css_class='col-md-6'),
                        Div('outcomes_year2015_sickle',css_class="col-md-6"),
                        Div('outcomes_year2015_rare',css_class="col-md-6"),
                        css_class='row',
                        ),
                ),


            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = Ext_centers
        exclude = ['center_id', 'author']
        list_display = ('title', 'pub_date', 'author')


class ExternalCentersOutcomes2Form(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExternalCentersOutcomes2Form, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        #self.fields['patient'].queryset = Demographic.objects.filter(patient_id=self.instance.patient)
        self.helper.field_class = 'col-md-8'
        self.helper.label_class = 'col-md-3'
        self.helper.layout = Layout(
            Fieldset(
                '&lt;b&gt;2. More measurements&lt;/b&gt;',
                Div(
                        #HTML(u'&lt;br/&gt;&lt;div class="col-md-9"&gt;&lt;h4&gt;&lt;b&gt;Molecular analysis&lt;/b&gt;&lt;/h4&gt;&lt;/div&gt;&lt;br/&gt;&lt;br/&gt;'),
                        Div('out_patients_married',css_class='col-md-6'),
                        Div('out_patients_divorced',css_class="col-md-6"),
                        Div('out_patients_single',css_class="col-md-6"),
                        Div('out_patients_cohabiting',css_class="col-md-6"),
                        Div('out_patients_parented_children',css_class="col-md-6"),
                        Div('out_thal_women_preg',css_class="col-md-6"),
                        Div('out_patients_splene',css_class="col-md-6"),
                        css_class='row',
                        ),
                ),


            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = Ext_centers
        exclude = ['center_id', 'author']
        list_display = ('title', 'pub_date', 'author')
</code></pre>

<p>Example from <code>models.py</code></p>

<pre><code>class Ext_centers(models.Model):
    center_id = models.AutoField(primary_key=True)

    center_city  = models.CharField('City',max_length=45, null=True, blank=True)
    center_country  = models.CharField('Country',max_length=45, null=True, blank=True)
    center_name_of_medical_director  = models.CharField('Name of medical director',max_length=45, null=True, blank=True)
    center_name_of_respondent  = models.CharField('Name of respondent',max_length=45, null=True, blank=True)
    center_status_of_respondent  = models.CharField('Status of respondent',max_length=45, null=True, blank=True)
    center_telephone = models.IntegerField('Telephone', null=True,blank=True)
    center_email = models.EmailField('E-mail',null=True,blank=True)
    center_fax = models.IntegerField('Fax',null=True,blank=True)
    center_website = models.CharField('Website',max_length=45, null=True, blank=True)
    ....

    pub_date = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User)
    history = HistoricalRecords()


    def __str__(self):
        return self.name_of_center
</code></pre>

<p>As I result for each form I have a new row in my table containing only values from the specific form. I need to store all these form's data into one table.</p>

<p>In the place of save You need "update"</p>

<p>Here is an example :</p>

<pre><code>    ext_cent_stored = Ext_centers.objects.get(center_id=ext_cent_object.center_id) 

    form = ExternalCentersForm(request.POST, instance=ext_cent_stored)
                if form.is_valid():
                     form.save()

    form = ExternalCentersDiagnosticForm(request.POST, prefix='extcentDiagn',instance=ext_cent_stored)
                if form.is_valid():
                     form.save()

    form = ExternalCentersOutcomesForm(request.POST,prefix='extcentOutcomes', instance=ext_cent_stored)
                if form.is_valid():
                     form.save()

    form = ExternalCentersOutcomes2Form(request.POST,prefix='extcentOutcomesTwo', instance=ext_cent_stored)
                if form.is_valid():
                     form.save()
</code></pre>

<p>Use this for every save method and you will not lose old data.</p>

<p>Thanks.</p>

python django django-models django-forms django-views