2017-04-06 106 views
1

我想保存多個數據與自動遞增的ID(1,2,3 ...等),數據庫將數據保存到數據庫,而不是在同一列。用戶可以動態添加輸入字段,最後單擊提交按鈕將數據保存在數據庫中,每個數據庫都有不同的ID(自動遞增的ID)。動態添加輸入字段和使用Django

我做了HTML和J查詢添加輸入字段時,單擊button.But我沒有任何想法使用django.I什麼也沒做,我view.py文件來存儲這些存儲在數據庫。

enter image description here 這是使用HTML和jQuery

+0

標識的自動遞增領域。您需要預先定義用戶可以在模型中添加哪些文件。不建議向數據庫添加列是依賴於用戶的。如果您想從JS發送JSON數據並將其存儲在數據庫中,我建議您使用django rest框架。 – giaco

回答

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

只有一行值存儲在數據庫中。 – malarvz

+0

我已經更新了一些logic.also許多行如何通過 – ketanmodi

+0

請評價我的觀點打印檢查 – ketanmodi