コンテンツへスキップ

form, a tag

HTMLのformを使って、ユーザーが入力した値を自由に利用することができます。
以下の例では、ユーザーに英語の文章を入力してもらい、各単語の出現頻度を出力する仕組みを作成しています。

入力値の加工はviews.pyまたは出力画面のHTMLで実施可能です。
複雑な加工はpythonを利用できるviews.pyで実施した方が賢明です。

a tagはHTMLにリンクを張る手法の1つです。

設定方法

  1. この記事を実施していることが前提となります。
  1. ホームページのHTMLの中に、テキスト入力欄とクリック用のボタンを作成します。
    action=でボタンクリック後の遷移先ページを指定します。
<h1>Home page html</h1>

<form action="{% url 'count_url' %}">
    <textarea cols="40" rows="5" name="fulltext"></textarea>
    <br />
    <input type="submit" value="Count!" />
</form>
  1. urls.pyで遷移先ページのURLを設定します。
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('count/', views.count, name='count_url')
]
  1. views.pyでユーザーが入力した値を読み込み、好きなように加工し、遷移先のHTMLに加工後の値を引き渡します。
from django.http import HttpResponse
from django.shortcuts import render
import operator

def home(request):
    return render(request, 'home.html')

def count(request):
    fulltext = request.GET['fulltext']
    wordlist = fulltext.split()

    worddictionary = {}
    for word in wordlist:
        if word in worddictionary:
            worddictionary[word] += 1
        else:
            worddictionary[word] = 1
    sortedwords = sorted(worddictionary.items(), key=operator.itemgetter(1), reverse=True)

    return render(request, 'count.html', {'fulltext': fulltext, 'count': len(wordlist), 'worddictionary': sortedwords})
  1. 最後に、遷移先のHTMLを設定します。view.pyから受け取った値を、簡易的に加工して出力しています。a tagを利用し、href=で指定したページへのリンクを表示しています。
<h1>There are {{ count }} words in your text</h1>

<a href="{% url 'home' %}">Start Again</a>

<h1>Your Text:</h1>
{{ fulltext }}

<h1>Frequency:</h1>
{% for word, counttotal in worddictionary %}
    {{ counttotal }} - {{ word }} <br />
{% endfor %}