From c36f846b605163c0f98ce9161aca14cda66f4ea4 Mon Sep 17 00:00:00 2001 From: Lukas Vinclav Date: Tue, 6 Aug 2024 09:27:34 +0200 Subject: [PATCH] feat: warn unsaved form (#655) --- README.md | 3 +++ src/unfold/admin.py | 1 + src/unfold/static/unfold/js/app.js | 23 +++++++++++++++++++++ src/unfold/templates/admin/change_form.html | 2 +- 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 65ac9a84..e4b5c69e 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,9 @@ class CustomAdminClass(ModelAdmin): # Display fields in changeform in compressed mode compressed_fields = True # Default: False + # Warn before leaving unsaved changes in changeform + warn_unsaved_form = True # Default: False + # Preprocess content of readonly fields before render readonly_preprocess_fields = { "model_field_name": "html.unescape", diff --git a/src/unfold/admin.py b/src/unfold/admin.py index c4c0c026..32d09f0b 100644 --- a/src/unfold/admin.py +++ b/src/unfold/admin.py @@ -236,6 +236,7 @@ class ModelAdmin(ModelAdminMixin, BaseModelAdmin): list_disable_select_all = False compressed_fields = False readonly_preprocess_fields = {} + warn_unsaved_form = False checks_class = UnfoldModelAdminChecks @property diff --git a/src/unfold/static/unfold/js/app.js b/src/unfold/static/unfold/js/app.js index 121fa45f..bc737798 100644 --- a/src/unfold/static/unfold/js/app.js +++ b/src/unfold/static/unfold/js/app.js @@ -8,8 +8,31 @@ window.addEventListener("load", (e) => { renderCharts(); filterForm(); + + warnWithoutSaving(); }); +/************************************************************* + * Warn without saving + *************************************************************/ +const warnWithoutSaving = () => { + let formChanged = false; + + Array.from( + document.querySelectorAll( + "form.warn-unsaved-form input, form.warn-unsaved-form select" + ) + ).forEach((field) => { + field.addEventListener("change", (e) => (formChanged = true)); + }); + + window.addEventListener("beforeunload", (e) => { + if (formChanged) { + e.preventDefault(); + } + }); +}; + /************************************************************* * Filter form *************************************************************/ diff --git a/src/unfold/templates/admin/change_form.html b/src/unfold/templates/admin/change_form.html index 7d946c53..b2912913 100644 --- a/src/unfold/templates/admin/change_form.html +++ b/src/unfold/templates/admin/change_form.html @@ -59,7 +59,7 @@ {% block content %}
-
+ {% csrf_token %} {% block form_top %}{% endblock %}