2
1

More than 1 year has passed since last update.

Django勉強シリーズ(1)Formクラスを使う

Posted at

1.Djangoでフォームを作成する方法

djangoでHTMLファイルにフォームを作成する方法はいくつかある。

①テンプレートに直接inputタグを記述して作成する

②forms.pyにforms.Formクラスを継承したフォームクラスを作成し利用

③forms.pyにモデル(forms.ModelForm)を利用したフォームクラスを作成し利用

今回は②の方法を用いてフォームを作成してみた

2.データをソートするためのプルダウンフォーム作成

①アプリケーションフォルダ内にデフォルトではforms.pyは作成されないのでまずはforms.pyを作り、その中に作りたいフォームのクラスを作成する

→forms.pyに記入することで細かな設定をすることができる

app/forms.py
from django import forms

フォームのフィールドの型はいくつか用意されている

フィールド一覧で参照したページ

今回はChoiceFieldを使ってみる
ChoiceFieldは画面上にプルダウンメニューを表示させることができる

app/forms.py
from django import forms

class SortForm(forms.Form): #forms.Formクラスを継承
  CHOICES = (('normal', 'ソート順選択'), ('maxtrophy', '最高トロ'),('position', '役職')) #プルダウン用の選択肢(key,value)

  choice = forms.fields.ChoiceField(
    choices = CHOICES,
    required = True,
    label = 'ソート順'
  )

②views.pyでテンプレートにフォームクラスを渡す

app/views.py
from django.shortcuts import render
from .forms import SortForm #先程作成したSortFormクラスをimport
from .models import UserModel #自分で作成したモデル(ソート対象のデータ、カラムにmaxtrophy,positionを持つ)

def mainfunc(request):
  object_list = UserModel.objects.all()
  if request.method == 'POST': #ソートが実行された場合
    sort_method = request.POST['choice']
    if sort_method != 'normal':
      object_list = UserModel.objects.order_by(sort_method).reverse()
    return render(request, 'app/main.html', {'object_list':object_list, 'form': SortForm()}) #Sortフォームを受け渡す
  else:
    return render(request, 'app/main.html', {'object_list':object_list, 'form': SortForm()}) #Sortフォームを受け渡す

③テンプレート(htmlファイル)の作成

templates/app/main.html
{% extends 'base.html' %}

{% block header %}
<div class="alert alert-primary" role="alert">
  <h3>メイン画面</h3>
</div>
{% endblock header %}

{% block content %}

<p><h2>メンバー</h2></p>

<form method="POST" action="">
  <input type="submit" value="ソートする"> 
!-- 選択された項目を送るためのボタン作成 -->
  {% for field in form %} <!-- views.pyからのSortFormクラスを受け取り順番に選択肢ごとにfor文を回す -->
  {{ field }}
  {% endfor %}
  {% csrf_token %}     <!-- formを作成する際には必ず必要 -->
</form>

<!-- 以下ソート用のデータを表にまとめる -->
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">名前</th>
        <th scope="col">最多トロフィー</th>
        <th scope="col">役職</th>
      </tr>
    </thead>
    <tbody>
      {% for item in object_list %}
      <tr>
        <th scope="row">{{ forloop.counter }}</th>
        <td>{{ item.username }}</td>
        <td>{{ item.maxtrophy }}</td>
        <td>{{ item.position }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

{% endblock content  %}

出来上がりイメージ
スクリーンショット 2021-12-26 14.38.44.png

今回はデータをソートするためのソート方法項目をまとめたプルダウンフォームを作成してみました。
まだまだDjango初心者ですが新たな学びはメモとしてまとめていこうと思います。

2
1
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
2
1