G
G
Gourii2021-03-20 14:33:31
Django
Gourii, 2021-03-20 14:33:31

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.

6055d9efe979b226971780.png

html code

<!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>


A piece of views.py

def update(request, dsend):
    if request.method == 'POST':
        print(dsend)


urls.py

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)
]


Two questions:
1) Where to add {% csrf_token %} in the Django template so that there are no errors in the logs:

Forbidden (CSRF token missing or incorrect.): /send/update/
[20/Mar/2021 14:25:38] "POST /send/update/ HTTP/1.1" 403 2513

2) Am I sending data from the template to views correctly at all?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2021-03-20
@fox_12

Haven't tested it, but something like this might work:

$.ajax({
                url: 'update/',
                ...
                beforeSend: function(request) {
                    return request.setRequestHeader('X-CSRF-Token', "{{ csrf_token }}");
                },
})

D
Dr. Bacon, 2021-03-20
@bacon

{% csrf_token %} will only work inside the form tag. And you send data with ajax, you just need to open the docks and read how to do it in this case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question