Django初心者です。
モデルから取得した内容をテンプレートに一覧表示させています。
各データに対してボタンを設置し、「delete」ボタンが押下された場合、該当データが削除され再度更新済みのモデル内容が同ページに表示されるようにしたいです。
templates/lists/index.html
1<div class="container"> 2 <div class="daily"> 3 <h2 class="title">Today</h2> 4 <form action="{% url 'lists:delete_record' %}" method="POST"> 5 {% csrf_token %} 6 <ul id="daily-content"> 7 {% for daily in daily_list %} 8 <li>{{ daily.content }}<input type="hidden" name="nameID" value="{{ daily.id }}"><button name="done" type="submit" value="{{ daily.id }}">done</button><button name="delete" type="submit" value="{{ daily.id }}">delete</button></li> 9 {% endfor %} 10 </ul> 11 </form> 12 </div> 13</div> 14 15以下省略…
しかしviews.pyにて以下のように記載をすると、def delete_recordのreturnで遷移先を記載しているだけなのでDBの内容が反映されなくなってしまいます。
lists/views.py
1from django.shortcuts import render 2 3# Create your views here. 4from django.http import HttpResponse, HttpRequest 5from .models import daily, reminder, objective 6from django.views.generic import ListView 7import logging 8 9class IndexView(ListView): 10 template_name = 'lists/index.html' 11 context_object_name = 'daily_list' 12 model = daily 13 14 def get_context_data(self, **kwargs): 15 context = super(IndexView, self).get_context_data(**kwargs) 16 context.update({ 17 'reminder_list': reminder.objects.all(), 18 'objective_list': objective.objects.all(), 19 }) 20 return context 21 22 def get_queryset(self): 23 return daily.objects.all() 24 25index = IndexView.as_view() 26 27 28def delete_record(request): 29 if request.method == 'POST': 30 if 'delete' in request.POST: 31 deleteID = request.POST.get('nameID') 32 record = daily.objects.get(id=deleteID) 33 record.delete() 34 return render(request, 'lists/index.html') 35
lists/urls.py
1from django.urls import path 2from . import views 3 4from django.contrib import admin # 追加 5from django.views.generic import TemplateView # 追加 6 7app_name = 'lists' 8urlpatterns = [ 9 path('', views.index, name='index'), 10 path('delete_record', views.delete_record, name='delete_record'), 11 12] 13
該当レコードをdeleteした後、「IndexView」クラスの処理を再度行いたい場合どのように記載をすればいいのかわからず、アドバイスをいただけますと嬉しいです。
回答する前に今作られているDjangoのディレクトリ構造を見せてほしいです。あと「path('', views.index, name='index')」のパスは「/」であってますか?
ご回答ありがとうございます。ディレクトリ構造は以下のようになっております。
todo_django
├── config
│ ├── __init__.py
│ ├── __pycache__
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── lists
│ ├── __init__.py
│ ├── __pycache__
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── manage.py
├── static
│ ├── css
│ ├── images
│ └── js
└── templates
├── base.html
└── lists
└── index.html
>あと「path('', views.index, name='index')」のパスは「/」であってますか?
実際には「/lists/」でページが表示されます。読み込まれているのは「templates/lists/index.html」です。
もしご質問にそれた回答になってしまっていたらすみません。
ありがとうございます、大丈夫です!
回答したので確認お願いします
ご回答ありがとうございます。redirect('/lists/')で無事目的の処理ができました!
回答2件
あなたの回答
tips
プレビュー