【发布时间】:2017-03-27 09:54:03
【问题描述】:
我正在尝试将表单中的数据存储到我的数据库中,我正在使用 Django-Python 作为后端。
这是我的 HTML 表单
<form>
<center>
<div class="container-fluid">
<div class="row">
<div class="col-sm-5" style="background-color:white;">
<p>First name:<br></p>
</div>
<div class="col-sm-6" style="background-color:white;">
<p><input type="text" id="firstname"><br></p>
</div>
<div class="col-sm-5" style="background-color:white;">
<p>Last name:<br></p>
</div>
<div class="col-sm-6" style="background-color:white;">
<p><input type="text" id="lastname"><br></p>
</div>
<div class="col-sm-5" style="background-color:white;">
<p>Email ID:<br></p>
</div>
<div class="col-sm-6" style="background-color:white;">
<p><input type="text" id="email"><br></p>
</div>
<div class="col-sm-5" style="background-color:white;">
<p>Delivery Address:<br></p>
</div>
<div class="col-sm-6" style="background-color:white;">
<p><input type="text" id="address"><br></p>
</div>
<div class="col-sm-5" style="background-color:white;">
<p>Contact Number:<br></p>
</div>
<div class="col-sm-6" style="background-color:white;">
<p><input type="number" id="number"><br></p>
</div>
</div>
</div>
</center>
<h1> </h1>
<p>"Payment mode:- Cash On Delivery,</p>
<p>All payment have to be done to the delivery boy by cash."</p><br>
<center>
<button onclick = "submitform()" class="button" style="background-color:black;color:#ffcb04;padding:5px 10px 5px 10px;border-radius: 10px">Submit</button>
</center>
</form>
这是我的 javascript/Jquery/Ajax
function submitform(){
firstname = $("#firstname").val()
lastname = $("#lastname").val()
email = $("#email").val()
address = $("#address").val()
number = $("#number").val()
string = {
'firstname' :firstname,
'lastname' : lastname,
'email' : email,
'address' : address,
'number' : number
}
json_string = JSON.stringify(string);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/orders/store-order-details/',
data: json_string,
success: function(data) {
window.location.href = "/confirmation/";
}
});
}
这是我的 Django views.py
def store_order_details(request):
received_json_data = json.loads(request.body)
customer_obj = Customer(first_name=received_json_data['first_name'], last_name=received_json_data['last_name'],
email_ID=received_json_data['email_id'], contact_number=received_json_data['number'],
address=received_json_data['address'])
print(customer_obj)
customer_obj.save()
print(received_json_data['data'])
return Response(status.HTTP_201_CREATED)
我无法找出其中的错误,因为我觉得这在表面上是可以的。
问题是数据没有存储在数据库中。我不确定数据是否由 Ajax 发布。我觉得视图中的 Python 代码很好。但是我怀疑 json.loads 是否会起作用。
我在终端中收到此错误
“POST /orders/store-order-details/HTTP/1.1”403 2274
当我使用 URL 参数测试我的视图时
我收到此错误
JSON 对象必须是 str,而不是 'bytes'
所有表单输入都是字母数字
【问题讨论】:
-
你没有提到确切的错误
-
什么错误?你没有提到什么问题
-
问题是数据没有存储在数据库中。我不确定数据是否由 Ajax 发布。我觉得视图中的 Python 代码很好。但是我怀疑 json.loads 是否会起作用。
-
只发送纯字符,字母数字
-
改变了。它仍然给出错误
标签: javascript jquery python ajax django