ボタンを押したらGamingViewのpost
メソッドのみが実行されてほしいのですが、__init__
メソッドから行われてしまいます。どのようにすればよいでしょうか?
以下詳細です
answer_form
に文字列を入力してボタンを押すとPOSTが実行され、GamingViewのself.params[answers]
にappendしたい- 画面をリロードしたくないのでfetchによる非同期通信を行なっている
質問用に抜粋・簡略化しています。よろしくお願いします。
python
1# views.py 2class GamingView(generic.TemplateView): 3 4 template_name = 'gaming.html' 5 6 def __init__(self): 7 # viewとhtml間で受け渡しされる変数. 何度も使い回すのでインスタンス変数として宣言 8 self.params = { 9 'answers': [], 10 } 11 12 def get(self, request, *args, **kwargs): 13 return render(request, self.template_name, self.params) 14 15 # ボタンを押したらこのメソッドだけが行われてほしい 16 def post(self, request, *args, **kwargs): 17 answer = request.POST.get('answer') # 入力された解答 18 self.params['answers'].append(answer) 19 return JsonResponse(self.params)
python
1# urls.py 2from django.urls import path 3from .import views 4app_name = 'game' 5 6urlpatterns = [ 7 path('', views.TitleView.as_view(), name='title'), # タイトル画面 8 path('gaming/', views.GamingView.as_view(), name='gaming'), # ゲーム中の画面 9]
html
1<!-- gaming.html --> 2<body> 3 <div class="home-content wrapper"> 4 <form id="answer_form" name="answer_form"> 5 {% csrf_token %} 6 <input id="answer" type="text" name="answer", value=""> 7 <button id="submit-button" class="button-game" type="submit">解答</button> 8 </form> 9 <h3 class="question" id="hoge_output" >出力先</h3> 10 </div> 11 12 <script > 13 const answer_form = document.getElementById('answer_form') 14 answer_form.addEventListener('submit', (e) => { 15 e.preventDefault() 16 const url = '{% url "gaming" %}' 17 const answer = document.getElementById('answer') 18 const body = new URLSearchParams() 19 body.append('answer', answer.value) 20 21 fetch('', { 22 method: 'POST', 23 body: body, 24 headers: { 25 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 26 'X-CSRFToken': csrftoken, 27 }, 28 }) 29 .then((response) => { 30 return response.json() 31 }) 32 .then((response) => { 33 answer.value = '' 34 // gamingviewのself.paramsのanswersの長さを出力する 35 document.getElementById('hoge_output').innerHTML = response.answers.length 36 }) 37 .catch((error) => { 38 console.log(error) 39 }) 40}) 41 </script> 42</body>
回答1件
あなたの回答
tips
プレビュー