Django中Bootstrap Modal加载Note更新表单数据问题求助
问题解决步骤
1. 优化表单配置
修改forms.py,移除unit字段(编辑Note时无需更改所属Unit,避免误操作):
class NoteModelForm(forms.ModelForm): class Meta: model = Note fields = ('title', 'note', 'created_date') widgets = { 'created_date': DateInput(), }
2. 调整Unit详情视图
移除单一的note_form,为每个Note生成绑定实例的表单并传入模板:
def unit_detail(request, pk): unit = Unit.objects.prefetch_related('notes').get(id=pk) # 为每个note创建对应表单,存入字典 note_forms = { note.id: NoteModelForm(instance=note) for note in unit.notes.all() } context = { "unit": unit, "note_forms": note_forms, } return render(request, "units/unit_detail.html", context)
3. 添加模板过滤器
在项目根目录创建templatetags/custom_filters.py,实现字典取值过滤器:
from django import template register = template.Library() @register.filter def get_item(dictionary, key): return dictionary.get(key)
4. 更新Unit详情页模板
修改unit_detail.html,加载过滤器并为每个Note传入对应表单:
{% extends "base.html" %} {% load custom_filters %} {% block content %} <div class="card" style="width: 48rem;"> <div class="card-body"> <h5 class="card-title">{{ unit.number }}</h5> <h6 class="card-subtitle mb-2 text-muted" id="unit-id">{{ unit.id }}</h6> <p class="card-text">Note:</p> {% for note in unit.notes.all %} <!-- 传递当前note和对应表单到模态框模板 --> {% include 'units/note_update.html' with note=note note_form=note_forms|get_item:note.id %} <table> <tbody> <th scope="row">{{ note.title }}</th> <td>{{ note.unit }}</td> <td>{{ note.note }}</td> <td>{{ note.created_date }}</td> <td id="note-id">{{ note.id }}</td> <td><a data-bs-toggle="modal" data-bs-target="#exampleModal{{ note.id }}" class="card-link" type="button" id="note-edit-btn">Edit</a> <a href="#" class="card-link">Delete</a> </td> </tbody> </table> {% endfor %} </div> </div>
5. 简化NoteUpdateView代码
class NoteUpdateView(generic.UpdateView): template_name = "units/note_update.html" form_class = NoteModelForm queryset = Note.objects.all() def get_success_url(self): return reverse("unit-detail", kwargs={'pk': self.object.unit.id})
核心问题说明
之前所有模态框共用一个未绑定实例的空表单,导致无法加载原有Note数据,提交时也无法定位到目标Note。现在每个Note对应独立的绑定表单,初始化时会自动填充原有数据,提交后精准更新指定Note。
内容的提问来源于stack exchange,提问作者Taka
相关产品推荐
相关产品推荐

