1
votes

I want to save the multiple data to database with autoincremented id (1,2,3...etc),not in same column. User can dynamically add input fields and finally click submit button to save data in database with different id(auto incremented id) for each.

I did HTML and J query for Add Input Fields when Click button.But I don't have any idea to store that in Database using django.I did nothing in my view.py file to store this.

enter image description here This is the code for Add fields using HTML and Jquery

1
Id is autoincremented field by default. You need to predefine which fileds can user add in your model. It is not recommended that adding columns to database is user dependant. I suggest you using django rest framework if you want to send JSON data from JS and store it in database. - Jan Giacomelli

1 Answers

2
votes

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/")