I am trying to save this HTML form in my table in the database, but I am getting "None" error. I have been on this for some hour. Please any help will be appreciated
Please, how do i fix this
The is the HTML order.html i created
<form action="" method="post" id="payment-form">
<input type="text" id="first_name"
name="first_name"
value="{{request.user.first_name}}">
<textarea type="text" id="address" name="address"
placeholder="1234 Main St" required></textarea>
<button id="submit" >
Proceed to Payment
</button>
</form>
Here is my views.py
def add(request):
basket = Basket(request)
if request.POST.get("action") == "post":
order_key = request.POST.get("order_key")
user_id = request.user.id
baskettotal = basket.get_total_price()
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
address = request.POST.get("address")
print(first_name, last_name, address)
order = Order.objects.create(
first_name = first_name,
address=address,
total_paid=baskettotal,
)
order_id = order.pk
response = JsonResponse({"success": "Order created"})
return response
The js file
<script type="text/javascript">
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
</script>
CodePudding user response:
First of all you don't have to post extra value action to determine post request you jsut have to use request.method
it will return you all available method you can check for specific method by adding check like this
if request.method == "POST":
note : allways use capitalized method while adding this check
and I'm not sure where you're calling makePayment()
function and whatever data you're trying to access in your python script you've to pass it through ajax{data:{}}
like this
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
order_key : "your order key",
first_name : $('#first_name').val(),
last_name : $('#last_name').val(),
address : $('#address').val()
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
and than access access it like this
def add(request):
basket = Basket(request)
if request.method == "POST":
order_key = request.POST.get("order_key")
#....all other fields