Значение, которое я получил из jQuery, является NoneType в django

Я хочу реализовать функцию, которая обновляет график и отображает количество обновлений при нажатии кнопки.

Однако, когда я пытаюсь получить параметр в view.py с помощью jQuery, он возвращает NoneType вместо предполагаемого значения. В чем проблема?

Также, не знаю, связано ли это, но когда я использую console.log() в функции jQuery, в консоли инструментов разработчика браузера нет никакого вывода. Похоже, это никак не связано с режимом "только для ошибок" или фильтром, который я ввел в Console.

Ошибка
TypeError в /graph/update_graph
Аргумент int() должен быть строкой, байтоподобным объектом или числом, а не 'NoneType'

Спасибо.

Вот код

views.py

from xml.etree.ElementInclude import include
from django.shortcuts import render
from django.http import JsonResponse
from . import graphdata

def index(request):
    fig = graphdata.get_scatter_figure()

    plot_fig = fig.to_html(fig, include_plotlyjs=False)
    return render(request, 'graph/index.html', {'graph':plot_fig})

def update_graph(request):
    graph = graphdata.get_scatter_figure()
    grahp_html = graph.to_html(graph, include_plotlyjs=False)
    cnt = int(request.POST.get('count'))  # <-- This is the error point
    cnt += 1
    data = {
        "graph": grahp_html,
        "count": cnt,
        }
    return JsonResponse(data)

index.html

<!DOCTYPE html>
<html lang="ja">

<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
   <!--  plotly JS Files  -->
   <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
   <meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>

<body>
   <div id="update-num">0</div>
   <div id="update-text">update</div>
   <form id="graph-update-form" action="{% url 'graph:update_graph' %}" method="POST">
      {% csrf_token %}
      <button type="submit" id="upadate-bt">update</button>
   </form>
   <div class="graph" id="scatter-graph">{{ graph| safe }}</div>
   <!-- jquery script -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
      $("#update-graph-from").on("submit", function(e){
         e.preventDefault();

         // These outputs will not be displayed in the console
         console.log('hello');
         console.log($("#update-num").text());

         $.ajax(
            {
               url: "{% url 'graph:update_graph' %}",
               type: "POST",
               data: {
                  count: $("#update-num").text(),
               },
               dataType: "json",
            }
         )
         .done(function(response){
            $("#update-num").remove();
            $("#update-num").prepend(response.count);
         });
      });
   </script>
</body>

</html>

urls.py

from django.urls import path
from . import views

app_name = "graph"

urlpatterns = [
    path('', views.index, name='index'),
    path('update_graph', views.update_graph, name='update_graph'),
]

У вас есть форма с id="graph-update-form" и вы отправляете форму с id="update-graph-from". Также, поскольку вы уже установили url в вашем ajax, вам не нужны action="{% url 'graph:update_graph' %}" и method="POST" в вашей форме. Также вы можете напрямую установить ваш ajax response vale, вам не нужно remove элемент, так что вам не нужно добавлять. Измените index.html как

<!DOCTYPE html>
<html lang="ja">

<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
   <!--  plotly JS Files  -->
   <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
   <meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>

<body>
   <div id="update-num">0</div>
   <div id="update-text">update</div>
   <form id="graph-update-form">
       {% csrf_token %}
       <button type="submit" id="upadate-bt">update</button>
   </form>
   <div class="graph" id="scatter-graph">{{ graph| safe }}</div>
   <!-- jquery script -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
       $("#graph-update-form").on("submit", function (e) {
        e.preventDefault();

        // These outputs will not be displayed in the console
        console.log('hello');
        console.log($("#update-num").text());

        $.ajax({
            url: "{% url 'update_graph' %}",
            type: "POST",
            'headers': {
                'X-CSRFToken': $('#graph-update-form').find('input[name="csrfmiddlewaretoken"]').val()
            },
            data: {
                count: $("#update-num").text(),
            },
            dataType: "json",
        })
        .done(function (response) {
            $("#update-num").text(response.count);
        });
    });
Вернуться на верх