ユーザ用ツール

サイト用ツール


50_dialy:2023:06:03

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン前のリビジョン
次のリビジョン
前のリビジョン
50_dialy:2023:06:03 [2023/06/03 07:34] matsui50_dialy:2023:06:03 [2023/06/03 07:54] (現在) matsui
行 64: 行 64:
 ] ]
 </code> </code>
 +
 +===== 3.urls.py修正 =====
 +
 +作成したtestappアプリのviewへアクセスするURL Pathを作成
 +<code>
 +import testapp.views as test_view
 +
 +urlpatterns = [
 +    path('test/', test_view.View.as_view())
 +]
 +</code>
 +
 +===== 4.view.pyを修正 =====
 +
 +GET されたら、ただテンプレートを表示。
 +POST されたら、POSTされた値を表示するだけの、view
 +
 +<code|testapp/views.py>
 +from django.shortcuts import render
 +
 +# Create your views here.
 +from django.shortcuts import render, redirect, get_object_or_404
 +from django.views.generic import TemplateView
 +
 +from testapp.models import *
 +import logging
 +logging.basicConfig(level=logging.INFO)
 +logger = logging.getLogger(__name__)
 +
 +class View(TemplateView):
 +    template_name = "test.html"
 +
 +    def get(self, request):
 +        context = {}
 +        return render(self.request, self.template_name, context)
 +    def post(self, request):
 +        context = {
 +                'action': request.POST.get('action'),
 +                'name1': request.POST.get('name1'),
 +                'name2': request.POST.get('name2'),
 +                }
 +        logger.info(request.POST)
 +        return render(self.request, self.template_name, context)
 +</code>
 +
 +===== 5.template作成 =====
 +
 +作成したアプリフォルダの下に、templatesフォルダを作成し、view.pyで記述したtest.htmlを用意
 +<code|testapp/templates/test.html>
 +Hello World!
 +<br>
 +
 +{% if action %}
 +action = {{ action }}
 +<h1>
 +{{ action }} が押されました。
 +</h1>
 +name1 = {{name1}}<br>
 +name2 = {{name2}}
 +{% endif %}
 +<form method='post' action='/test/'>
 + {% csrf_token %}
 + <input type='hidden' name='name1' value='value1'>
 + <input type='hidden' name='name2' value='value2'>
 + <button type='submit' name='action' value='Button1'>Button1</button>
 + <button type='submit' name='action' value='Button2'>Button2</button>
 +</form>
 +
 +</code>
 +
 +
 +===== 6.ページ確認 =====
 +
 +GET後
 +{{:50_dialy:2023:06:pasted:20230603-075113.png?400}}
 +
 +POST後
 +{{:50_dialy:2023:06:pasted:20230603-075122.png?400}}
  
 {{tag>Django python}} {{tag>Django python}}
50_dialy/2023/06/03.1685777666.txt.gz · 最終更新: 2023/06/03 07:34 by matsui