我想用ajax代碼更新我的數據庫的內容使用引導模態窗體。但我的數據庫不會更新與窗體中提供的輸入。表單工作得很好,但我沒有看到數據庫中更新的內容。哪裏不對 ???爲什麼下面的代碼沒有更新數據庫?
<div class="container">
<h1> {{ username }} </h1>
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<form id="new_user_form">
{% csrf_token %}
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="form-group" >
<label for="usr">Username:</label>
<input type="text" name="username" class="form-control input-lg" id="username">
<label for="passwordd">Password:</label>
<input type="password" name="password" class="form-control input-sm" id="password">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="submit">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="/static/bootstrap 3/js/bootstrap.min.js"></script>
Ajax代碼:
<script>
$(document).on('submit','#new_user_form',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/testapp/registered/",
data: {
username: $('#username').val(),
password: $('#password').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
sucess: function(){
alert("Registeration successfully.")
}
error: function(jqXHR, textStatus, errorThrown)
{
alert(textStatus, errorThrown);
}
});
});
</script>
views.py:
from django.shortcuts import render
from testapp.models import User
def index(request):
template = 'index.html'
return render(request,template)
def create_user(request):
if request.method == 'POST':
User.objects.create(
username = request.POST['username'],
password = request.POST['password'],
)
User.save()
return render(request,'testapp/index.html',{'username':request.POST['username']})
請我搜索整個互聯網,並沒有什麼:(
的html代碼幫助
testapp \ urls.py:
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^$', views.index, name="Index"),
url(r'^registered/$', views.create_user, name="registered"),
]
你在'create_user'視圖中測試過使用ipdb進行調試嗎?如果你調用'request.POST',你會得到什麼? –
什麼是ipdb?以及我創建了我的主要項目的副本,並猜測該副本更新數據庫,但主項目仍然沒有更新數據庫,我做了兩個項目的檢查,我得到500內部服務器錯誤這裏是圖像的錯誤:https://postimg.org/image/tim44b9nl/ – Ahtisham
最有可能'User.save()'導致錯誤。因爲'User'類沒有保存屬性。只要擺脫那條線。 'create'已經爲你保存對象 – karthikr