[Answered ]-Dynamically add input fields and save data to Database using django

2👍

HTML:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
   $(function(){
   var i =0;

  $('#adduser").click(function(){
      var AnswerHTML = "";
      AnswerHTML ='<div class="form-group" style="border: 1px solid;background-color: #ADD8E6">'
    +' <div class="col-xs-4"><input type="text" name="firstname'+i+'"> </input></div>'
    +' <div class="col-xs-4"><input type="text" name="age'+i+'">  </input></div>'
    +' <div class="col-xs-4"><input type="text" name="relation'+i+'"></input></div>'
    +'<i class="icon-trash" style="padding-left:20px;  cursor: pointer;"></i></div>';


  $('#divQuatationList').append(AnswerHTML);
  i++;
   $("#totallength").val(i);

 });
});
$(document).on("click",".icon-trash",function(e){

$(this).closest('.form-group').remove();
});
</script>

<body>
<div>
<p id='adduser' class='btn btn-info' >ADD</p>
</div>

<form class="form-horizontal row-border" action="{% url "Saveforms" %}" method="post">
<input type="hidden" id="totallength" name="totallength"  />
<div id="divQuatationList"></div>
<div class="col-md-12"><input type="submit" id="Submit" class="btn btn-info pull-right" value="SaveData"  />
</form>
</body>
</html>

 URL 

 url(r'^Saveforms/$', views.Saveforms, name='Saveforms'),


 Views

 def Saveforms(request):

 lenth =  request.POST['totallength']

 if request.POST:
    i = 0
    for index in range(i,int(lenth)):
        firstname =""
        age =""
        relation =""
        flag=0
        if 'firstname'+str(index) in request.POST:
            firstname= request.POST['firstname'+str(index)]
            flag = 1
        if 'age'+str(index) in request.POST:
            age= request.POST['age'+str(index)]
            flag = 1
        if 'relation'+str(index)  in request.POST:
            relation= request.POST['relation'+str(index)]         
            flag = 1

        if flag == 1: 

             UserName.objects.create(firstname=firstname,age=age,relation=relation)               

return HttpResponseRedirect("/dynamicform/Manageforms/")

Leave a comment