0 モデルの追加・更新・削除 #django みんなに公開

モデルの追加・更新・削除

testapp/urls.py

urlpatterns = [
    # ...
    path('insert/', UserView.insert, name='insert'),
    path('update/<int:id>/', UserView.update, name='update'),
    path('delete/<int:id>/', UserView.delete, name='delete'),
]

template

testapp/templates/users.html

      {% for user in users %}
        <!-- 一括処理ではない場合はformはusersの内側へ -->
        <form method="post" action="update/{{ user.id }}/">
          {% csrf_token %}
          <tr>
            <td>
              {{ user.id }}
            </td>
            <td>
              <input type="text" name="name" value="{{ user.name }}" />
            </td>
            <td>{{ user.created_at }}</td>
            <td>{{ user.updated_at }}</td>
            <td><input type="submit" name="update" value="更新" /></td>
            <td><input type="submit" name="delete" value="削除" /></td>
          </tr>
        </form>
      {% endfor %}
    </tbody>
  </table>
  <form method="post" action="insert">
    {% csrf_token %}
    名前 <input type="textbox" value="" name="username" />
    <input type="submit" name="insert" value="登録" />
  </form>

追加のview

testapp/views/user_view.py

    def insert(request):
        user=AppUser()
        user.name = request.POST.get('username', None)
        user.created_at = datetime.now()
        user.updated_at = datetime.now()
        user.save()
        return HttpResponseRedirect('/')

更新・削除・一括削除の振り分け

testapp/views/user_view.py

        if not request.POST.get('delete', None) == None:
            user = AppUser.objects.filter(id=userid).first()
            if not user == None:
                user.delete()
        if not request.POST.get('batch_delete', None) == None:
            ids_list = request.POST.getlist('batch_ids[]')
            print(ids_list)
            UserView.batch_delete(ids_list)
            return HttpResponseRedirect('/batch_delete')
        else:
            user = AppUser.objects.filter(id=userid).first()
            if not user == None:
                user.name = request.POST.get('name', None)
                user.updated_at = datetime.now()
                user.save()

更新のview

testapp/views/user_view.py

            user = AppUser.objects.filter(id=userid).first()
            if not user == None:
                user.name = request.POST.get('name', None)
                user.updated_at = datetime.now()
                user.save()

削除のview

testapp/views/user_view.py

            user = AppUser.objects.filter(id=userid).first()
            if not user == None:
                user.delete()
0

メモを他の人に見せる

このメモを見せたい人に、このURL(今開いているページのURLです)を教えてあげてください

コメント(0)

  • someone

  • someone