0
1

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でチェックボックスで送られきた複数のデータを、まとめて1件ずつレコードに保存する。

Last updated at Posted at 2024-01-20

概要

タイトルだと何をやろうとしているのかわかりづらいかもしれないが、
下記のようなイメージ。

例えば、こんなフォームがあるとする。

<form>
    <input type="checkbox" name="multi" value="data1">
    <input type="checkbox" name="multi" value="data2">
    <input type="checkbox" name="multi" value="data3">
    <input type="checkbox" name="multi" value="data4">
    <button type="submit" value="送信">
<form/>

複数にチェックを入れた状態で送信ボタンを押すと、
複数のデータが1件ずつレコードに保存される。

この例だと、仮に全部チェックを入れて送信したとするとDBではこのように保存される

id | multi
______________
 1 | data1
______________
 2 | data2
______________
 3 | data3
______________
 4 | data4

結論 getlistメソッドを使う

POSTで送られてきた配列データを処理するためのgetlistメソッドを使うと実現できる。
このような書き方になる。

views.py
#スケジュール新規登録処理
def add_post(request):

    if request.method == 'POST':
    
        #getlistメソッドで配列の受け取り
        selecteds = request.POST.getlist('multi')

        #ループで回して1件づつDBに保存
        for value in selecteds:
            SchoolSchedule.objects.create(multi=value) 
            
    #処理成功後に移動するページ
    return redirect('/index')

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?