LoginSignup
0
2

More than 3 years have passed since last update.

犬ですが何か?Django--初めてFormを使ってみるPOST送信の巻

Posted at

Formで送信してみる

こんにちは!柴犬のぽん太です。
今日はお風呂場でなすがままに体を洗ってもらいました。そのあと、なんだか自分じゃないみたいな変な感じがしたのでひたすら身体中を舐めていました。

さて、今日はフォームに挑戦です。

テンプレートにformを記述する

wan/templates/wan/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
    <form action="{% url 'wan:form' %}" method="POST">
        {% csrf_token %}
        <label for="message">message: </label>
        <input id="message" type="text" name="message">
        <input type="reset" value="cancel">
        <input type="submit" value="click">
    </form>
</body>
</html>

formを記載しました。{% url 'wan:form' %}とありますが、この中のwan:formが

の送信先を表していて、wan/urls.pyのurlpatternsにnameで登録しているアドレスを表しています。wan:formのうち、wanはwan/urls.py内で登録しているアプリ名です。

アプリ名の登録とurlpatternsの設定

wan/urls.py
from django.urls import path
from . import views

app_name = 'wan'

urlpatterns = [
    path('', views.index, name='index'),
    path('form', views.form, name='form'),
]

というわけです。app_name = 'wan'でアプリ名wanを登録しています。

views.py

ここでformを定義します。

views.py
from django.shortcuts import render

def index(request):
    params = {
        'title': 'Wan/Index',
        'message': "What's your message?",
    }
    return render(request, 'wan/index.html', params)

def form(request):
    message = request.POST['message']
    params = {
        'title': 'Wan/Index',
        'message': message,
    }
    return render(request, 'wan/index.html', params)

表示テスト

スクリーンショット 2020-08-28 22.32.52.png

次のようにメッセージを入力します。

スクリーンショット 2020-08-28 22.33.41.png

clickをクリックすると・・・

スクリーンショット 2020-08-28 22.34.49.png

メッセージの入力、フォームでの配信、受信して表示、のながれができました。

じゃあまたね!バイバイ!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2