この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:2
ページ更新者:T
更新日時:2018-12-12 03:21:57

タイトル: チュートリアル:電卓の作成
SEOタイトル: djangoで電卓の作成【python】

本稿ではdjangoで簡単な電卓を作成する方法を説明します。

※機能は非常にシンプルにします。(加算機能のみ)

本稿の目的はMVC(MVT)を用いた値の入出力です。

 

前提

・Pythonの導入済み(まだの方はこちら

・djangoの導入済み(まだの方はこちら

 

完成図

 

プロジェクトの作成

適当なプロジェクトを作成します。

python django-admin.py startproject django_projects

 

アプリケーションの作成

python manage.py startapp calculator

 

ルーティング処理

calculator/urls.pyを作成して以下の記述をする。

from django.urls import path

from . import views

urlpatterns = [

    path('', views.index, name='index'),

    path('calc', views.calc),

]

 

更にdjango_projects/urls.pyを修正する。

calculatorアプリのurls.pyにパスを通す。

from django.contrib import admin

from django.urls import include, path

urlpatterns = [

    path('calculator/', include('calculator.urls')),

    path('admin/', admin.site.urls),
]

 

共通テンプレートの作成

アプリケーションディレクトリ直下にtemplatesディレクトリを作成しましょう。

今後テンプレートは当ディレクトリに格納します。

以下はヘッダーなどを共通化するテンプレートです。

ファイル名はbase.htmlにします。

<!DOCTYPE html>

<html lang="ja">

        <head>

                <meta charset="UTF-8">

                <title>{% block title %}{% endblock title %}</title>

        </head>

        <body>

                {% block content %}

                {% endblock %}

        </body>

</html>

 

テンプレートの作成

実際の電卓画面の部分を作成します。

機能は加算のみにします。

ファイル名はindex.htmlにします。

{% extends "base.html" %}

{% block title %}電卓{% endblock title %}

{% block content %}

    <h1>djangoの加算電卓</h1>

    <form method="post" action="calc">

        {% csrf_token %}

        <input type="number" name="val1">
        +
        <input type="number" name="val2">

        <button type="submit"> = </button>

        {{ answer }}

    </form>

{% endblock %}

 

ビューの作成

from django.shortcuts import render


def index(request):

    return render(request, 'index.html')


def calc(request):

    val1 = int(request.POST['val1'])

    val2 = int(request.POST['val2'])

    answer = val1 + val2

    context = {

        'answer': answer,

    }

    return render(request, 'index.html', context)

 

http://127.0.0.1:8000/calculator/

で計算画面が開きます。