ajax通信でpythonファイルを実行したい
djangoでwebアプリケーションを作成中に出たエラーについてです。
簡単なHTML,CSSの実装を終え、pythonファイルの実行に移ろうと思い、調べた結果ajax通信を使うのが良いということだったので見様見真似で実装を試みました。
発生している問題・エラーメッセージ
'website' is not a registered namespace
該当のソースコード
HTML/base.html
{% load static %} <!doctype HTML> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> </head> <body> {% include "_navbar.html" %} {% block main %} コンテンツがありません {% endblock %} <button type="button" onclick="clickBtn()">判定</button><br> <input type="text" size="50" id="input_form"><br> <script> function clickBtn() { var txt = document.getElementById("input_form").value; $.ajax({ url: "{% url 'website:call_sample' %}", method: 'GET', data: {"input_data": txt}, dataType: "text", beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrf_token); } }, error: function(xhr, status, error) { console.log("error") } }) .done(function(data) { console.log("Success"); }); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } // ヘッダにcsrf_tokenを付与する関数 function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }; } </script> {% include "_footer.html" %} </body> </html>
pyhton/views.py
from django.views.generic import TemplateView from django.shortcuts import render from django.http import HttpResponse from .application import sample class IndexView(TemplateView): template_name ="index.html" def get_context_data(self): ctxt = super().get_context_data() ctxt["username"] = "Narimi" return ctxt class AboutView(TemplateView): template_name ="about.html" def get_context_data(self): ctxt = super().get_context_data() ctxt["num_services"] = 12345678 ctxt["skills"] = [ "Python", "HTML", "Javascript", "Java", ] return ctxt def call_sample(req): if req.method == 'GET': sample.write_sistem(req.GET.get("input_data")) return HttpResponse()
python/sample.py
def write_sistem(): matrix = [ [-1, -1, 1 ,0, 1, 1, 1, 1], [-1, 0, 0, 0, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0] ] for i in range(len(matrix)): for j in range(len(matrix[0])): if(matrix[i][j] == 1): if(j == len(matrix[0]) - 1): print('h') else: print('h', end='') if(matrix[i][j] == 0): if(j == len(matrix[0]) - 1): print('r') else: print('r', end='') if(matrix[i][j] == -1): if(j == len(matrix[0]) - 1): print(' ') else: print(' ', end='')
他、必要なファイル等あればコメントお願いします。
補足情報
まだまだ勉強中の初心者なので至らない点は多々あるかと思いますが、よろしくお願いいたします。
HTML,CSS,javascript,Java,Cなどは一通り学習しました。
まだ回答がついていません
会員登録して回答してみよう