我在支持项目信息组织的应用程序中正是这样做的。
我想有很多不同的方法可以解决这个问题,但我选择的路径是覆盖视图的 post 方法。以以下缩写视图中的代码为例:
class HomeView(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):
permission_required = 'app.view_project'
reviewtype = None
template_name = "home.html"
def post(self, request, *args, **kwargs):
""" a) There are two forms for each project accordion button
displayed by this HomeView and,
b) We are displaying those forms in a Bootstrap 5 'modal' (as
opposed to redirecting the user to a new view for the form(s))
Override the POST method for this view so that the forms can be
processed correctly.
"""
# Determine which form is being sent in the post request.
if 'owner' in request.POST:
# 'owner' was in the POST data: NoteForm was sent in
form = NoteForm(data=request.POST)
elif 'changed_by' in request.POST:
# 'changed_by' was in POST data: ReviewStatusForm was sent in
form = ReviewStatusForm(data=request.POST)
elif 'project_company_approval' in request.POST:
# 'project_company_approval' was in POST data: EditFieldForm was sent in
form = EditCompanyApprovalForm(
data=request.POST,
instance=Project.objects.get(project_number=request.POST['project_number']),
)
您会注意到视图会检查用户想要编辑的字段是否存在于 POST 数据中,如果存在,它会启动适当的表单并使用表单中存在的数据填充表单.
就模态本身而言,由以下模板处理:
{% load crispy_forms_tags %}
<!-- Button trigger modal -->
<i type="button" class="bi bi-pencil-square" style="color : green" data-bs-toggle="modal" data-bs-target="#editCompanyApprovalModal{{ project.project_number }}" onclick="open_modal({{ project.project_number }},'_project_approval','{{ project.project_approval }}')" ></i>
<!-- Modal -->
<div class="modal fade" id="editCompanyApprovalModal{{ project.project_number }}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel{{ project.project_number }}" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-body">
{% crispy form %}
</div>
</div>
</div>
</div>
希望这有助于回答您的问题?如果您还有什么想看的,请告诉我,我会看看我能做些什么来得到答案。
根据您的具体实现,您可能还必须重写视图的 get_context_data() 方法。
祝你好运。