Wednesday, 17 October 2012

Model formsets saving in the in Django models forms.

In case of the the FormSet in the django model forms, the save method is different from that of the forms, as fromset library is different from the form. For formset in the forms the "modelform_factory" is to be called in the views from the django. models. For this write the following line in the header of the file:
                        from django.forms.models import modelsformset_factory

and make a function in the views like,

def chemical_analysis(request):
ChemicalFormSet = modelformset_factory(chem_analysis)
if request.method=='POST':
                formset = ChemicalFormSet(request.POST, request.FILES)
                if formset.is_valid():
cd = formset.cleaned_data
return HttpResponseRedirect(reverse(''))
        return HttpResponse("There was an error with your submission. Please try again.")

formset = ChemicalFormSet()
return render_to_response('report/report_add_row.html', {'formset': formset}, context_instance=RequestContext(request))

In the file write the following in the header of the file;
                                     from django.forms.models import BaseModelFormSet

And made the models in the following way:

class chem_analysis(models.Model):
    s_no = models.CharField(max_length=255,blank=True)
    description = models.CharField(max_length=255,blank=True)
    result = models.CharField(max_length=255,blank=True)
    def __str__(self):
        return self.s_no
class Basechem_analysisFormSet(BaseModelFormSet):
    class Meta :
        model = chem_analysis

In the input form html file i.e report_add_row.html, call the formset in the following way:

{% extends "base.html" %}
{% load i18n %}

    <title>Gndec Ludhiana</title>

{% block content %}


<SCRIPT language="javascript">
        function addRow(tableID) {

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "text";

//            var cell2 = row.insertCell(1);
//            cell2.innerHTML = rowCount + 1;

   var cell2 = row.insertCell(1);
            var element2 = document.createElement("input");
            element2.type = "text";

            var cell3 = row.insertCell(2);
            var element3 = document.createElement("input");
            element3.type = "text";

   var cell4 = row.insertCell(3);
            var element4 = document.createElement("input");
            element4.type = "checkbox";

   var cell5 = row.insertCell(4);
            cell5.innerHTML = rowCount + 1;

function deleteRow(tableID) {
            try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;

            for(var i=0; i<rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[3].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {

            }catch(e) {


    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
    {% endif %}

    <form action="" method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
        {{ }}
<table width = "528px"> <tr>
</tr> </table>      

 <table id="dataTable" width="350px" border="">


<td>{{ form.s_no}}</td>
<td>{{ form.description}}</td>
<td>{{ form.result}}</td>
<TD><INPUT type="checkbox" name="chk"/></TD>
          {% if formset.can_delete %}
                <li>{{ form.DELETE }}</li>
            {% endif %}
    {% endfor %}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

        <input type="submit" value="Submit">


{% endblock %}


No comments:

Post a Comment