0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Django】POST無し GETのみでフォームの内容を取得して表示に反映させる

Last updated at Posted at 2023-01-27

フォームに入力した値によって表示内容を変えたい時に、POSTを使わずにフォーム内容を取得し、反映させる方法の備忘録

仕様

選択フォームで選んだものを、選択フォームの下部に表示するWebページ。

ソースコード

まずフォームを設置する。ここではSelectフォームとする。

form.py
class SelectForm(Form):
    select_sample = ChoiceField(
        widget=Select(),
        choices=[
            ("", "未選択"),
            ("01", "選択肢1"),
            ("02", "選択肢2"),
            ("03", "選択肢3"),
        ],
        required=False
    )

ビューファイルでフォーム送信内容を取得

view.py
template_name = "sample.html"

...

# もし送信されていたら
if form.is_valid():
    # 内容を取得する
    selected = int(form.cleaned_data.get("select_sample"))
    # 選択フォームの選択を取得した値で固定する
    form.fields['select_sample'].initial = [selected]

...

context = {
    ...
    "form": form,
    "selected": selected,
    ...
}
return render(request, self.template_name, context)

「フォームに入力された値を取得する」ではなく「パラメータの値を取得する」の場合は以下のようにできる。

views.py
selected = request.GET.get(key="select_sample", default="")
# 上記のようにNoneだった場合のdefaultも指定可能

htmlファイル。POSTは使っていないので{% csrf_token %}は必要ない。
{{ selected }}の部分に選択した内容が表示される。

sample.html
...

{{ form.select_sample }}
<button type="submit">更新</button>

{{ selected }}

...
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?