====== 2023.06.03 Django アプリ追加 ====== Django環境は、[[06_virtualization:05_container:27_docker_django|こちら]] で用意。 test_project ===== 1 アプリ作成 ===== docker-compose run web django-admin.py startapp [アプリ名] or docker-compose exec web python manage.py startapp [アプリ名] 例: docker-compose exec web python manage.py startapp testapp ===== 2 setting.py修正 ===== アプリ作成時点だと下記のようになってます。 プロジェクト名は「test_project」、アプリ名は「testapp」を例に説明 # tree ./ ./ ├── db.sqlite3 ├── manage.py ├── test_project │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-38.pyc │   │   ├── settings.cpython-38.pyc │   │   ├── urls.cpython-38.pyc │   │   └── wsgi.cpython-38.pyc │   ├── asgi.py │   ├── settings.py │   ├── urls.py │   └── wsgi.py └── testapp ├── __init__.py ├── admin.py ├── apps.py ├── migrations │   └── __init__.py ├── models.py ├── tests.py └── views.py アプリインストールの設定を追加 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testapp', ] ===== 3.urls.py修正 ===== 作成したtestappアプリのviewへアクセスするURL Pathを作成 import testapp.views as test_view urlpatterns = [ path('test/', test_view.View.as_view()) ] ===== 4.view.pyを修正 ===== GET されたら、ただテンプレートを表示。 POST されたら、POSTされた値を表示するだけの、view 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) ===== 5.template作成 ===== 作成したアプリフォルダの下に、templatesフォルダを作成し、view.pyで記述したtest.htmlを用意 Hello World!
{% if action %} action = {{ action }}

{{ action }} が押されました。

name1 = {{name1}}
name2 = {{name2}} {% endif %}
{% csrf_token %}
===== 6.ページ確認 ===== GET後 {{:50_dialy:2023:06:pasted:20230603-075113.png?400}} POST後 {{:50_dialy:2023:06:pasted:20230603-075122.png?400}} {{tag>Django python}}