django-formdefaults 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. django_formdefaults-0.5.0/.gitignore +47 -0
  2. django_formdefaults-0.5.0/CHANGELOG.md +167 -0
  3. django_formdefaults-0.5.0/LICENSE +21 -0
  4. django_formdefaults-0.5.0/PKG-INFO +405 -0
  5. django_formdefaults-0.5.0/README.md +364 -0
  6. django_formdefaults-0.5.0/pyproject.toml +104 -0
  7. django_formdefaults-0.5.0/src/formdefaults/__init__.py +3 -0
  8. django_formdefaults-0.5.0/src/formdefaults/_autosnap_backfill.py +29 -0
  9. django_formdefaults-0.5.0/src/formdefaults/admin.py +66 -0
  10. django_formdefaults-0.5.0/src/formdefaults/apps.py +15 -0
  11. django_formdefaults-0.5.0/src/formdefaults/core.py +151 -0
  12. django_formdefaults-0.5.0/src/formdefaults/forms.py +123 -0
  13. django_formdefaults-0.5.0/src/formdefaults/helpers.py +24 -0
  14. django_formdefaults-0.5.0/src/formdefaults/locale/pl/LC_MESSAGES/django.mo +0 -0
  15. django_formdefaults-0.5.0/src/formdefaults/locale/pl/LC_MESSAGES/django.po +47 -0
  16. django_formdefaults-0.5.0/src/formdefaults/management/__init__.py +0 -0
  17. django_formdefaults-0.5.0/src/formdefaults/management/commands/__init__.py +0 -0
  18. django_formdefaults-0.5.0/src/formdefaults/management/commands/dedupe_formdefaults.py +31 -0
  19. django_formdefaults-0.5.0/src/formdefaults/migrations/0001_initial.py +139 -0
  20. django_formdefaults-0.5.0/src/formdefaults/migrations/0002_django32.py +17 -0
  21. django_formdefaults-0.5.0/src/formdefaults/migrations/0003_formrepresentation_pre_registered.py +21 -0
  22. django_formdefaults-0.5.0/src/formdefaults/migrations/0004_unique_field_user.py +24 -0
  23. django_formdefaults-0.5.0/src/formdefaults/migrations/0005_unique_field_system.py +22 -0
  24. django_formdefaults-0.5.0/src/formdefaults/migrations/0006_formfielddefaultvalue_is_auto_snapshot.py +21 -0
  25. django_formdefaults-0.5.0/src/formdefaults/migrations/0007_backfill_is_auto_snapshot.py +34 -0
  26. django_formdefaults-0.5.0/src/formdefaults/migrations/__init__.py +0 -0
  27. django_formdefaults-0.5.0/src/formdefaults/models.py +188 -0
  28. django_formdefaults-0.5.0/src/formdefaults/permissions.py +51 -0
  29. django_formdefaults-0.5.0/src/formdefaults/registry.py +64 -0
  30. django_formdefaults-0.5.0/src/formdefaults/signals.py +60 -0
  31. django_formdefaults-0.5.0/src/formdefaults/static/formdefaults/modal.css +84 -0
  32. django_formdefaults-0.5.0/src/formdefaults/static/formdefaults/modal.js +89 -0
  33. django_formdefaults-0.5.0/src/formdefaults/templates/formdefaults/_button.html +8 -0
  34. django_formdefaults-0.5.0/src/formdefaults/templates/formdefaults/_modal_fragment.html +19 -0
  35. django_formdefaults-0.5.0/src/formdefaults/templates/formdefaults/_user_edit_form.html +10 -0
  36. django_formdefaults-0.5.0/src/formdefaults/templatetags/__init__.py +0 -0
  37. django_formdefaults-0.5.0/src/formdefaults/templatetags/formdefaults.py +25 -0
  38. django_formdefaults-0.5.0/src/formdefaults/urls.py +18 -0
  39. django_formdefaults-0.5.0/src/formdefaults/util.py +17 -0
  40. django_formdefaults-0.5.0/src/formdefaults/views.py +114 -0
@@ -0,0 +1,47 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ .Python
8
+ build/
9
+ dist/
10
+ *.egg-info/
11
+ *.egg
12
+
13
+ # Unit test / coverage reports
14
+ .coverage
15
+ .coverage.*
16
+ .cache
17
+ .pytest_cache/
18
+ htmlcov/
19
+ .tox/
20
+ coverage.xml
21
+ *.cover
22
+
23
+ # Virtual envs
24
+ .venv/
25
+ venv/
26
+ env/
27
+
28
+ # IDE
29
+ .idea/
30
+ .vscode/
31
+
32
+ # OS
33
+ .DS_Store
34
+ Thumbs.db
35
+
36
+ # Claude Code harness state
37
+ .claude/
38
+
39
+ # uv
40
+ uv.lock
41
+
42
+ # Dev scaffolding (AI plans/specs, contain personal paths)
43
+ docs/superpowers/
44
+
45
+ # Local
46
+ *.log
47
+ example_project/db.sqlite3
@@ -0,0 +1,167 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.5.0] — 2026-05-11
9
+
10
+ ### Added
11
+
12
+ - **System-wide defaults from the popup.** A second "System defaults"
13
+ button next to the personal one opens the same modal bound to
14
+ `FormFieldDefaultValue` rows with `user=NULL`. Modal is visibly flagged
15
+ (amber accent, "applies to ALL users" notice) to avoid scope mistakes.
16
+ - `formdefaults.views.SystemFormDefaultsView` (`formdefaults:system-edit`
17
+ URL) — backs the new popup; reuses `build_user_defaults_form(user=None)`
18
+ and validates via the permission hook.
19
+ - `formdefaults.permissions.can_edit_system_wide_defaults(user, form_repr=None, form_class=None)`
20
+ — pluggable permission hook. Resolution order: per-form class attribute
21
+ `formdefaults_can_edit_system_wide(user, form_repr) -> bool` → settings
22
+ `FORMDEFAULTS_CAN_EDIT_SYSTEM_WIDE` (dotted path) → default
23
+ (`user.is_superuser`).
24
+ - Demo: `SearchForm` in `example_project` opts out of system-wide editing
25
+ via the per-form attribute, exercising the hook end-to-end.
26
+ - README "Screenshots" section embedding three rendered shots (regular
27
+ user, admin both-buttons, admin system modal) under
28
+ `docs/screenshots/`.
29
+ - Polish translations for the new strings ("System defaults",
30
+ system-wide warning text, modal help).
31
+
32
+ ### Changed
33
+
34
+ - `{% formdefaults_button form %}` now renders a second button only when
35
+ the permission hook returns True for the request user — otherwise the
36
+ output is unchanged.
37
+ - Popup closes automatically on a successful save (HTTP 200). Errors
38
+ (HTTP 400) still re-render in place with field-level error messages.
39
+
40
+ ## [0.4.1] — 2026-05-10
41
+
42
+ ### Added
43
+
44
+ - HTML `title` tooltip on every override checkbox in the popup —
45
+ hovering explains the toggle.
46
+ - Help text in the popup modal explaining the checkbox-vs-value
47
+ contract, so users discover the UX without reading docs.
48
+ - Polish translation shipped in
49
+ `src/formdefaults/locale/pl/LC_MESSAGES/django.{po,mo}`.
50
+
51
+ ### Changed
52
+
53
+ - Package templates (`_button.html`, `_modal_fragment.html`) now use
54
+ English source strings wrapped in `{% trans %}`. Polish-speaking
55
+ installs see the same text via `LANGUAGE_CODE='pl'`.
56
+ - example_project is now fully internationalised: English source plus
57
+ a Polish `.po`/`.mo`, language switcher in nav, `LocaleMiddleware`
58
+ wired up.
59
+ - README "Per-user popup" section: removed obsolete "Empty input
60
+ clears the override" sentence (superseded by v0.4.0's override
61
+ checkbox).
62
+
63
+ ## [0.4.0] — 2026-05-10
64
+
65
+ ### Added
66
+
67
+ - Per-field override toggle in the popup edit form. Each value field
68
+ has a companion `_override_<name>` checkbox rendered to its left.
69
+ Unchecked → the field is **not** written as an override on save (and
70
+ any existing override is deleted). Checked → the value is upserted as
71
+ the user's override, regardless of what the value is.
72
+ - `_user_edit_form.html` template uses a new `form.field_pairs()` helper
73
+ that yields `(override_checkbox, value_field)` tuples in `fields_set`
74
+ order.
75
+ - `modal.js` auto-checks the override checkbox when the user edits a
76
+ field's value (input/change events). The user can manually uncheck it
77
+ to revert.
78
+ - Default initial value for the popup field is now the currently-effective
79
+ default (user override if present, else system-wide), so the user can
80
+ see what they're getting and edit from there.
81
+
82
+ ### Changed (BREAKING)
83
+
84
+ - `build_user_defaults_form().save()` no longer treats empty input as
85
+ "delete this override". The override checkbox controls write/delete
86
+ exclusively. POST data must include `_override_<name>=on` for any
87
+ field the caller wants to upsert.
88
+ - The popup template `_user_edit_form.html` now expects the form to
89
+ expose `field_pairs()`. Custom templates overriding it must adapt.
90
+
91
+ ## [0.3.0] — 2026-05-10
92
+
93
+ ### Added
94
+
95
+ - `FormFieldDefaultValue.is_auto_snapshot: bool` — flag identifying rows
96
+ that came from `Form.initial` automatically and should be kept in sync
97
+ with the code. Cleared on every UI edit (popup or Django admin),
98
+ making the value "sticky".
99
+ - `update_form_db_repr` now refreshes value of rows where
100
+ `is_auto_snapshot=True` and value drifted from current
101
+ `form_field.initial`. Sticky rows are never touched.
102
+ - Data migration `0007_backfill_is_auto_snapshot` backfills the flag for
103
+ existing rows: True if `value == form_field.initial`, False otherwise.
104
+ - `formdefaults._autosnap_backfill.resolve_initial` — helper used by the
105
+ backfill migration; importable from tests.
106
+
107
+ ### Changed
108
+
109
+ - Popup save (`build_user_defaults_form().save()`) and admin save
110
+ (`FormRepresentationAdmin.save_formset`) both clear
111
+ `is_auto_snapshot` on every write so user/admin overrides become
112
+ sticky immediately.
113
+
114
+ ## [0.2.0] — 2026-05-10
115
+
116
+ ### Added
117
+
118
+ - `register_form` decorator and `FORMDEFAULTS_FORMS` setting for
119
+ pre-registration of forms; snapshot is taken on `post_migrate`.
120
+ - `pre_registered` flag on `FormRepresentation`.
121
+ - Per-user popup edit UX:
122
+ - `UserFormDefaultsView` (GET fragment / POST save) and
123
+ `formdefaults.urls`.
124
+ - `{% formdefaults_button %}` template tag.
125
+ - Vanilla-JS modal in `static/formdefaults/modal.js` (no jQuery/HTMX
126
+ dependency).
127
+ - `build_user_defaults_form` for programmatic per-user override editing.
128
+ - `dedupe_formdefaults` management command for migrating older databases.
129
+ - `example_project/` demonstrating all three registration paths.
130
+ - Unique constraint on `FormFieldDefaultValue(field, user)` for non-NULL
131
+ users + partial unique on `(field) WHERE user IS NULL` for system-wide
132
+ rows + index on `(parent, user)`.
133
+
134
+ ### Fixed
135
+
136
+ - `FormDefaultsMixin.get_initial` now passes `request.user` so per-user
137
+ overrides apply via the mixin (the previous version always returned
138
+ system-wide values).
139
+ - Race condition on first render of an unsnapshotted form when two requests
140
+ hit at once (`update_form_db_repr` now wraps the body in
141
+ `transaction.atomic` and swallows `IntegrityError` from concurrent
142
+ inserts).
143
+ - `FormRepresentationManager.get_or_create_for_instance` now seeds `label`
144
+ with `full_name` so admin never sees an empty label.
145
+
146
+ ### Changed
147
+
148
+ - Per-process freshness cache in `core.get_form_defaults` skips redundant
149
+ `update_form_db_repr` calls within a 60-second window.
150
+ - Test suite now runs against PostgreSQL via testcontainers (Docker
151
+ required) instead of in-memory SQLite, matching the production target.
152
+
153
+ ## [0.1.0] — 2026-05-09
154
+
155
+ ### Added
156
+
157
+ - Initial public release. Extracted from
158
+ [iplweb/bpp](https://github.com/iplweb/bpp) where it lived as the
159
+ in-tree `formdefaults` Django app.
160
+ - `FormRepresentation`, `FormFieldRepresentation`, `FormFieldDefaultValue`
161
+ models: store default values per form, per field, optionally per user.
162
+ - `FormDefaultsMixin` for class-based views: drop-in `get_initial()`
163
+ that pulls saved defaults for the current user.
164
+ - `core.get_form_defaults(form_instance, label=None, user=None)` —
165
+ programmatic access for non-CBV use.
166
+ - Two pre-existing migrations preserved verbatim from the original
167
+ in-tree app (initial schema + Django 3.2 JSONField alter).
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michał Pasternak and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,405 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-formdefaults
3
+ Version: 0.5.0
4
+ Summary: Per-user, database-backed default values for Django forms — lets users (and admins) save the values they typed last time.
5
+ Project-URL: Homepage, https://github.com/iplweb/django-formdefaults
6
+ Project-URL: Repository, https://github.com/iplweb/django-formdefaults
7
+ Project-URL: Issues, https://github.com/iplweb/django-formdefaults/issues
8
+ Project-URL: Changelog, https://github.com/iplweb/django-formdefaults/blob/main/CHANGELOG.md
9
+ Author-email: Michał Pasternak <michal.dtz@gmail.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: defaults,django,form-defaults,forms,initial-values,per-user
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 4.2
17
+ Classifier: Framework :: Django :: 5.0
18
+ Classifier: Framework :: Django :: 5.1
19
+ Classifier: Framework :: Django :: 5.2
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: License :: OSI Approved :: MIT License
22
+ Classifier: Operating System :: MacOS :: MacOS X
23
+ Classifier: Operating System :: POSIX
24
+ Classifier: Operating System :: POSIX :: Linux
25
+ Classifier: Programming Language :: Python
26
+ Classifier: Programming Language :: Python :: 3
27
+ Classifier: Programming Language :: Python :: 3 :: Only
28
+ Classifier: Programming Language :: Python :: 3.10
29
+ Classifier: Programming Language :: Python :: 3.11
30
+ Classifier: Programming Language :: Python :: 3.12
31
+ Classifier: Programming Language :: Python :: 3.13
32
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
33
+ Requires-Python: >=3.10
34
+ Requires-Dist: django>=4.2
35
+ Provides-Extra: test
36
+ Requires-Dist: psycopg[binary]>=3; extra == 'test'
37
+ Requires-Dist: pytest-django>=4.8; extra == 'test'
38
+ Requires-Dist: pytest>=7; extra == 'test'
39
+ Requires-Dist: testcontainers[postgres]>=4; extra == 'test'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # django-formdefaults
43
+
44
+ [![tests](https://github.com/iplweb/django-formdefaults/actions/workflows/tests.yml/badge.svg)](https://github.com/iplweb/django-formdefaults/actions/workflows/tests.yml)
45
+ [![PyPI version](https://img.shields.io/pypi/v/django-formdefaults.svg)](https://pypi.org/project/django-formdefaults/)
46
+ [![Python versions](https://img.shields.io/pypi/pyversions/django-formdefaults.svg)](https://pypi.org/project/django-formdefaults/)
47
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
48
+
49
+ Database-backed default values for Django forms. Plug it into any Django form
50
+ in one line and admins (system-wide) plus end-users (personal overrides) can
51
+ curate `Form.initial` from the UI.
52
+
53
+ Originally extracted from [iplweb/bpp](https://github.com/iplweb/bpp).
54
+
55
+ ## Screenshots
56
+
57
+ | Regular user | Superuser |
58
+ |---|---|
59
+ | ![Per-user defaults only](docs/screenshots/user-personal-only.png) | ![Both buttons](docs/screenshots/admin-both-buttons.png) |
60
+ | One button — opens the popup that edits *their own* override. | Two buttons — adds a second popup for editing the system-wide default that every user sees. |
61
+
62
+ System-wide editor (admins only — by default `is_superuser`, overridable
63
+ per-form or globally via a hook):
64
+
65
+ ![System-wide defaults modal](docs/screenshots/admin-system-modal.png)
66
+
67
+ ## Why?
68
+
69
+ Django forms usually default to whatever a developer hard-coded in
70
+ `Form.initial` — fine for a brand-new form, painful when the same user
71
+ fills the same form weekly with the same five fields. This package lets
72
+ admins curate defaults system-wide from the UI, and lets each user
73
+ override their own defaults via a popup. No code changes per form.
74
+
75
+ ## Features
76
+
77
+ - **Two editing scopes** — system-wide (admins) and per-user (end users),
78
+ both available from a popup next to the form. Per-user overrides shadow
79
+ system-wide values.
80
+ - **Permission hook** — `formdefaults_can_edit_system_wide(user, form_repr)`
81
+ decides who sees the "System defaults" button. Default: `user.is_superuser`.
82
+ Overridable per-form via a class attribute or globally via the
83
+ `FORMDEFAULTS_CAN_EDIT_SYSTEM_WIDE` setting.
84
+ - **Three ways to register a form** — `@register_form` decorator,
85
+ `FORMDEFAULTS_FORMS` setting (for forms you don't own), or zero
86
+ registration (snapshot on first render via `FormDefaultsMixin` /
87
+ `get_form_defaults`).
88
+ - **Vanilla-JS popup**, no jQuery / HTMX dependency. Renders a modal
89
+ with one input per form field, pre-filled with the currently-effective
90
+ default. Companion checkbox per field decides whether to upsert or
91
+ clear the override.
92
+ - **Auto-snapshot lifecycle** — rows tracking the code-level `Form.initial`
93
+ auto-refresh when developers change `initial=...`, but become sticky
94
+ the moment a user/admin edits them in the UI.
95
+ - **JSON-storable defaults** — covers the common Django field types
96
+ (numbers, strings, booleans, dates/datetimes/times, `ModelChoiceField`
97
+ PKs); non-serialisable lambdas/callables keep working at the form
98
+ level but aren't persisted.
99
+ - **Optional in-form HTML** — each form representation has
100
+ `html_before`/`html_after` text fields available as
101
+ `formdefaults_pre_html` / `formdefaults_post_html` in the form's
102
+ `initial` dict.
103
+
104
+ ## Idea
105
+
106
+ When a form is rendered, `django-formdefaults`:
107
+
108
+ 1. **Builds or refreshes a representation of the form in the DB** — its set
109
+ of fields, their order, types and labels, and a snapshot of `Form.initial`.
110
+ 2. **Lets you set default values per field** — e.g. a boolean that should
111
+ always default to `True`, a date that should always default to the current
112
+ month, an integer with a fixed initial.
113
+ 3. **Exposes two editing scopes**:
114
+ - **System-wide** — any superuser edits in Django admin (one default per
115
+ field, applied to everyone).
116
+ - **Per-user** — each logged-in user overrides their own copy via a popup
117
+ rendered next to the form. Their override shadows the system-wide value.
118
+
119
+ A form's DB representation can be created in **three ways**:
120
+
121
+ - `@register_form` decorator on the Form class — snapshot at Django startup
122
+ (`post_migrate`).
123
+ - `FORMDEFAULTS_FORMS` setting — list of dotted paths, also snapshot at
124
+ startup. Useful for forms you don't own.
125
+ - **No registration** — snapshot happens on first render via
126
+ `get_form_defaults()` / `FormDefaultsMixin`.
127
+
128
+ ## Installation
129
+
130
+ Using [uv](https://docs.astral.sh/uv/) (recommended):
131
+
132
+ ```bash
133
+ uv add django-formdefaults
134
+ ```
135
+
136
+ Using pip:
137
+
138
+ ```bash
139
+ pip install django-formdefaults
140
+ ```
141
+
142
+ `INSTALLED_APPS`:
143
+
144
+ ```python
145
+ INSTALLED_APPS = [
146
+ # ...
147
+ "formdefaults",
148
+ ]
149
+ ```
150
+
151
+ `urls.py` (only required if you want the per-user popup):
152
+
153
+ ```python
154
+ urlpatterns = [
155
+ # ...
156
+ path("formdefaults/", include("formdefaults.urls")),
157
+ ]
158
+ ```
159
+
160
+ Run migrations:
161
+
162
+ ```bash
163
+ ./manage.py migrate
164
+ ```
165
+
166
+ ## Supported versions
167
+
168
+ ### Python
169
+
170
+ | 3.10 | 3.11 | 3.12 | 3.13 |
171
+ |------|------|------|------|
172
+ | ✓ | ✓ | ✓ | ✓ |
173
+
174
+ ### Django × Python
175
+
176
+ | Django | 3.10 | 3.11 | 3.12 | 3.13 | Status |
177
+ |---------|------|------|------|------|---------------------------------|
178
+ | 4.2 LTS | ✓ | ✓ | ✓ | — | EOL April 2026 |
179
+ | 5.0 | ✓ | ✓ | ✓ | — | EOL April 2025 |
180
+ | 5.1 | ✓ | ✓ | ✓ | ✓ | EOL December 2025 |
181
+ | 5.2 LTS | ✓ | ✓ | ✓ | ✓ | Active LTS (extended Apr 2028) |
182
+ | 6.0 | — | — | ✓ | ✓ | Pre-release (testing on `--pre`)|
183
+
184
+ Cells reflect what CI actually exercises — see
185
+ [`.github/workflows/tests.yml`](.github/workflows/tests.yml).
186
+
187
+ ## Quick start
188
+
189
+ ### Path 1 — Decorator (recommended for forms you own)
190
+
191
+ ```python
192
+ # myapp/forms.py
193
+ from django import forms
194
+ from formdefaults import register_form
195
+
196
+ @register_form(label="Monthly report")
197
+ class MonthlyReportForm(forms.Form):
198
+ year = forms.IntegerField(initial=2026)
199
+ month = forms.ChoiceField(choices=[(i, str(i)) for i in range(1, 13)])
200
+ ```
201
+
202
+ Snapshot is created on `migrate`.
203
+
204
+ ### Path 2 — Setting (for forms you don't own)
205
+
206
+ ```python
207
+ # settings.py
208
+ FORMDEFAULTS_FORMS = [
209
+ "thirdparty.forms.SomeForm",
210
+ "myapp.forms.UserSettingsForm",
211
+ ]
212
+ ```
213
+
214
+ Optional class-level `formdefaults_label = "..."` becomes the row's label;
215
+ otherwise the class name is used.
216
+
217
+ ### Path 3 — Ad-hoc (no registration)
218
+
219
+ In a CBV, mix in `FormDefaultsMixin`:
220
+
221
+ ```python
222
+ from formdefaults.helpers import FormDefaultsMixin
223
+
224
+ class MonthlyReportView(FormDefaultsMixin, FormView):
225
+ form_class = MonthlyReportForm
226
+ title = "Monthly report"
227
+ ```
228
+
229
+ In an FBV, call `get_form_defaults`:
230
+
231
+ ```python
232
+ from formdefaults.core import get_form_defaults
233
+
234
+ initial = get_form_defaults(MonthlyReportForm(), user=request.user)
235
+ form = MonthlyReportForm(initial=initial)
236
+ ```
237
+
238
+ Either way, snapshot is created on first render.
239
+
240
+ ## Editing defaults
241
+
242
+ ### System-wide — popup (preferred)
243
+
244
+ When the current user passes the
245
+ `formdefaults_can_edit_system_wide(user, form_repr)` permission check
246
+ (default: `is_superuser`), `{% formdefaults_button form %}` renders a
247
+ second button — **System defaults** — that opens the same popup but bound
248
+ to `FormFieldDefaultValue` rows with `user=NULL`. The modal is visibly
249
+ flagged so admins don't mistakenly edit the wrong scope.
250
+
251
+ To restrict or expand who can edit system-wide defaults:
252
+
253
+ ```python
254
+ # settings.py — global override
255
+ FORMDEFAULTS_CAN_EDIT_SYSTEM_WIDE = "myapp.permissions.can_edit_fd_system"
256
+ ```
257
+
258
+ ```python
259
+ # myapp/forms.py — per-form override (wins over the global one)
260
+ class SecretForm(forms.Form):
261
+ formdefaults_can_edit_system_wide = staticmethod(
262
+ lambda user, form_repr: user.is_superuser and user.username == "alice"
263
+ )
264
+ ```
265
+
266
+ ### System-wide (Django admin)
267
+
268
+ Still available at `/admin/formdefaults/formrepresentation/` — pick a form
269
+ by label, then for each field add or edit a `FormFieldDefaultValue` row
270
+ with `User` empty.
271
+
272
+ The `FormRepresentation` row also has `html_before` and `html_after` text
273
+ fields, useful for surfacing in-form legends, contextual help, or a quick
274
+ note. They land in the form's `initial` dict under
275
+ `formdefaults_pre_html` and `formdefaults_post_html`. Render them in your
276
+ template however you like:
277
+
278
+ ```django
279
+ {{ form.initial.formdefaults_pre_html|safe }}
280
+ {{ form }}
281
+ {{ form.initial.formdefaults_post_html|safe }}
282
+ ```
283
+
284
+ ### Per-user (popup next to the form)
285
+
286
+ In your template:
287
+
288
+ ```django
289
+ {% load formdefaults static %}
290
+
291
+ <form method="post">
292
+ {% csrf_token %}
293
+ {{ form }}
294
+ <button type="submit">Submit</button>
295
+ </form>
296
+
297
+ {% formdefaults_button form %}
298
+
299
+ <script src="{% static 'formdefaults/modal.js' %}" defer></script>
300
+ <link rel="stylesheet" href="{% static 'formdefaults/modal.css' %}">
301
+ ```
302
+
303
+ > Place `{% formdefaults_button form %}` **outside** the `<form>` element — the modal injects its own `<form>` for saving overrides, and HTML5 forbids nesting forms.
304
+
305
+ The button only renders for authenticated users. Clicking it opens a modal
306
+ with one input per form field, pre-filled with the currently-effective
307
+ default value (your override if you have one, otherwise the system-wide
308
+ value).
309
+
310
+ Each field in the popup has a small checkbox to its left. The checkbox
311
+ controls whether your edit becomes an override:
312
+
313
+ - Unchecked → leave the field alone; the system-wide default applies to
314
+ you.
315
+ - Checked → save the value next to it as your personal override.
316
+
317
+ The checkbox auto-checks when you actually edit the field, so the common
318
+ flow is "type your new value, save". Uncheck if you want to delete a
319
+ previously-saved override.
320
+
321
+ ## Try it locally
322
+
323
+ ```bash
324
+ git clone https://github.com/iplweb/django-formdefaults
325
+ cd django-formdefaults/example_project
326
+ python manage.py migrate
327
+ python manage.py runserver
328
+ ```
329
+
330
+ Visit `http://127.0.0.1:8000/`. Three forms demonstrate all three registration
331
+ paths. Create a superuser (`./manage.py createsuperuser`) to try system-wide
332
+ editing in `/admin/`.
333
+
334
+ ## Public API
335
+
336
+ | Symbol | Purpose |
337
+ |---|---|
338
+ | `formdefaults.register_form` | Decorator: register a Form class for startup snapshot. |
339
+ | `formdefaults.helpers.FormDefaultsMixin` | CBV mixin: provides `get_initial()`. |
340
+ | `formdefaults.core.get_form_defaults(form, label=None, user=None, update_db_repr=True)` | Snapshot + return `{field_name: value}`. |
341
+ | `formdefaults.core.update_form_db_repr(form, form_repr, user=None)` | Lower-level: refresh DB representation. |
342
+ | `formdefaults.forms.build_user_defaults_form(form_repr, user, data=None)` | Build the popup edit form. |
343
+ | `formdefaults.views.UserFormDefaultsView` | View backing the per-user popup endpoint. |
344
+ | `formdefaults.views.SystemFormDefaultsView` | View backing the system-wide popup endpoint. |
345
+ | `formdefaults.permissions.can_edit_system_wide_defaults(user, form_repr=None, form_class=None)` | Resolve the permission hook (per-form attr → setting → default). |
346
+ | `{% formdefaults_button form %}` | Template tag rendering the personal button — and, if the hook allows, the system-defaults button. |
347
+ | `formdefaults.models.FormRepresentation` / `FormFieldRepresentation` / `FormFieldDefaultValue` | DB models. |
348
+
349
+ ## Storage
350
+
351
+ Three tables:
352
+
353
+ ```
354
+ FormRepresentation
355
+ full_name (PK) # "myapp.forms.MonthlyReportForm"
356
+ label # human-readable
357
+ pre_registered # True if registered via decorator/setting
358
+ html_before, html_after
359
+
360
+ FormFieldRepresentation
361
+ parent → FormRepresentation
362
+ name, label, klass, order
363
+ unique_together (parent, name)
364
+
365
+ FormFieldDefaultValue
366
+ parent → FormRepresentation
367
+ field → FormFieldRepresentation
368
+ user → AUTH_USER_MODEL # nullable; null = system-wide
369
+ value (JSON)
370
+ is_auto_snapshot # True until first UI edit; sticky after
371
+ unique constraint (field, user) for non-NULL users
372
+ unique constraint (field) WHERE user IS NULL for system-wide
373
+ ```
374
+
375
+ ## Limitations & gotchas
376
+
377
+ - Forms identified by fully qualified Python path. Renaming or moving a Form
378
+ class invalidates the saved defaults.
379
+ - Only fields whose `initial` is JSON-serialisable get a stored default.
380
+ Lambdas / callables on `initial` keep working at the form level but aren't
381
+ persisted.
382
+ - `FormFieldDefaultValue.clean()` re-instantiates the form to validate typed
383
+ values. Forms with heavy `__init__` cost slow down admin saves.
384
+ - The popup is opt-in: it only works if you include `formdefaults.urls`,
385
+ load the template tag, and serve the static JS/CSS.
386
+ - `is_auto_snapshot` is set to True heuristically for pre-0.3.0 rows
387
+ during the data migration: rows whose value matches the form's
388
+ current `initial` become `True` (the row looks untouched), the rest
389
+ become `False`. False positives happen rarely (someone deliberately
390
+ edited the value to match the code default and the data migration
391
+ can't tell). False positives become real on the next code change —
392
+ the value is treated as auto-snapshot and refreshed.
393
+
394
+ ## Running the tests
395
+
396
+ ```bash
397
+ pip install -e ".[test]"
398
+ pytest
399
+ ```
400
+
401
+ Tests run against PostgreSQL via [testcontainers](https://testcontainers-python.readthedocs.io/) — Docker is required on the test machine.
402
+
403
+ ## License
404
+
405
+ MIT — see [LICENSE](LICENSE).