如何使用 JsonResponse 将错误消息发送到 Django 通用 DeleteView 确认页面

How to send error message to the Django generic DeleteView Confirmation Page using JsonResponse

我正在尝试使用 确认页面 使用 Django 通用 DeleteView。设置按预期工作。

后来更改了业务逻辑以防止 删除 如果有子实例分配给被删除的对象,在模型中使用 on_delete=models.PROTECT

并将DeleteView修改为:

class TerritoryDeleteView(LoginRequiredMixin, DeleteView):
    template_name = ".../trty_delete.html"
    model = Territory
    success_url = reverse_lazy('territories_list')

    # THE FOLLOWING MODIFICATION DONE:
    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        try:
            self.object.delete()
            return HttpResponseRedirect(success_url)
        except ProtectedError:
            error_message = "This object can't be deleted, as an Outlet is already assigned to the Territory..."
            return JsonResponse(error_message, safe=False)

以上(修改后的)视图工作正常。但是,如果遇到 ProtectedErrorerror_message 将显示在 空白 浏览器页面中。

如何在确认页面(模板)中显示 error_message

首先,更改您的 delete(...) 方法以捕获 ProtectedError 错误(您已经完成了) 然后 将错误消息作为上下文数据传递给模板 as

class TerritoryDeleteView(LoginRequiredMixin, DeleteView):
    template_name = ".../trty_delete.html"
    model = Territory
    success_url = reverse_lazy('territories_list')

    <b>def delete(self, request, *args, **kwargs):
        try:
            return super().delete(request, *args, **kwargs)
        except ProtectedError:
            self.object = self.get_object()
            context = self.get_context_data(
                object=self.object,
                error="Any error msg"
            )
            return self.render_to_response(context)</b>

但是,这还不够,我们还必须更新模板文件

<form method="post">{% csrf_token %}
    <b>{% if error %}
        {{ error }}</b>
    {% else %}
        <p>Are you sure you want to delete "{{ object }}"?</p>
        <input type="submit" value="Confirm">
    {% endif %}

</form>

注意: 这可能不完全适合你的情况,但是,这可能会给你一个想法如何很好地管理错误消息。