Answer the question
In order to leave comments, you need to log in
How to send data from template to Django views?
I don’t understand how to send data from the html template to views so that processing takes place in the procedure. Completely confused.
There is a page with two buttons and an input field.
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Send Data to Server</title>
<script src="{% static "js/jquery-3.5.1.min.js" %}""></script>
<link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}"" />
<script>
function send_data(){
$.ajax({
url: 'update/',
type: 'post',
data: $(".pole").val,
success: function() {console.log('Save')},
datatype: 'json',
});
};
</script>
</head>
<body>
<input value="Home" type="button" onclick="location.href='/'" /><br>
<input id="pole" type="text" placeholder="Test Text" ><br>
<button onclick="send_data()" id="bsend" class="btn btn-success" >Send</button>
</body>
</html>
def update(request, dsend):
if request.method == 'POST':
print(dsend)
from django.contrib import admin
from django.urls import path, include
from get_data import views
urlpatterns = [
path('', views.root),
path('asset/', views.index),
path('asset2/', views.index2),
path('add/', views.add_record),
path('send/update/', views.update),
path('send/', views.send)
]
Forbidden (CSRF token missing or incorrect.): /send/update/
[20/Mar/2021 14:25:38] "POST /send/update/ HTTP/1.1" 403 2513
Answer the question
In order to leave comments, you need to log in
Haven't tested it, but something like this might work:
$.ajax({
url: 'update/',
...
beforeSend: function(request) {
return request.setRequestHeader('X-CSRF-Token', "{{ csrf_token }}");
},
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question