django-htmx-cbv 0.0.1.dev1__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.
- django_htmx_cbv-0.0.1.dev1/LICENSE +21 -0
- django_htmx_cbv-0.0.1.dev1/PKG-INFO +165 -0
- django_htmx_cbv-0.0.1.dev1/README.md +149 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/__init__.py +0 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/apps.py +9 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/checks.py +59 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/future.py +107 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/middleware.py +236 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/py.typed +0 -0
- django_htmx_cbv-0.0.1.dev1/django_htmx_cbv/views.py +387 -0
- django_htmx_cbv-0.0.1.dev1/pyproject.toml +60 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Geoffrey B. Eisenbarth
|
|
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,165 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: django-htmx-cbv
|
|
3
|
+
Version: 0.0.1.dev1
|
|
4
|
+
Summary: Django class-based views, tailored for htmx
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Geoffrey Eisenbarth
|
|
8
|
+
Author-email: geoffrey.eisenbarth@gmail.com
|
|
9
|
+
Requires-Python: >=3.14
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Requires-Dist: django (>=6.0.0,<7.0.0)
|
|
13
|
+
Requires-Dist: django-htmx (>=1.27.0,<2.0.0)
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# Django Class Based Views for HTMX
|
|
17
|
+
|
|
18
|
+
[](https://codecov.io/gh/geoffrey-eisenbarth/django-htmx-cbv)
|
|
19
|
+
|
|
20
|
+
`django-htmx-cbv` provides HTMX-friendly mixins and views for common Django class-based view workflows.
|
|
21
|
+
|
|
22
|
+
## Requirements
|
|
23
|
+
|
|
24
|
+
- Python 3.14+
|
|
25
|
+
- Django 6.0+
|
|
26
|
+
- django-htmx
|
|
27
|
+
|
|
28
|
+
This package assumes Django 6.0 template partial support.
|
|
29
|
+
It does not require `django-template-partials`.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
Install the package and `django-htmx`:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install django-htmx-cbv django-htmx
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Or with Poetry:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
poetry add django-htmx-cbv django-htmx
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Django setup
|
|
46
|
+
|
|
47
|
+
Add the app to `INSTALLED_APPS`:
|
|
48
|
+
|
|
49
|
+
```py
|
|
50
|
+
INSTALLED_APPS = [
|
|
51
|
+
# ...
|
|
52
|
+
"django_htmx_cbv",
|
|
53
|
+
]
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Add middleware in this order:
|
|
57
|
+
|
|
58
|
+
```py
|
|
59
|
+
MIDDLEWARE = [
|
|
60
|
+
# Django middleware...
|
|
61
|
+
|
|
62
|
+
"django_htmx.middleware.HtmxMiddleware",
|
|
63
|
+
"django_htmx_cbv.middleware.HtmxPartialTemplateMiddleware",
|
|
64
|
+
"django_htmx_cbv.middleware.HtmxVaryMiddleware",
|
|
65
|
+
"django_htmx_cbv.middleware.HtmxMessageMiddleware",
|
|
66
|
+
"django_htmx_cbv.middleware.HttpVerbViewMiddleware",
|
|
67
|
+
|
|
68
|
+
# Other middleware...
|
|
69
|
+
]
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Notes:
|
|
73
|
+
|
|
74
|
+
- `django_htmx.middleware.HtmxMiddleware` must run before the `django_htmx_cbv` middleware.
|
|
75
|
+
- `HtmxMessageMiddleware` must come after Django's `MessageMiddleware`.
|
|
76
|
+
- `HttpVerbViewMiddleware` should come after Django's `CsrfViewMiddleware`.
|
|
77
|
+
|
|
78
|
+
The package registers a Django system check for the `HtmxMiddleware` dependency/order.
|
|
79
|
+
|
|
80
|
+
## Template partials
|
|
81
|
+
|
|
82
|
+
This library expects Django 6.0 partial syntax:
|
|
83
|
+
|
|
84
|
+
```django
|
|
85
|
+
<!doctype html>
|
|
86
|
+
<html lang="en">
|
|
87
|
+
<body>
|
|
88
|
+
{% include "messages.html" %}
|
|
89
|
+
{% partialdef main %}
|
|
90
|
+
<main>
|
|
91
|
+
<h1>Example</h1>
|
|
92
|
+
{% partialdef content %}
|
|
93
|
+
<div id="content">Hello</div>
|
|
94
|
+
{% endpartialdef content %}
|
|
95
|
+
</main>
|
|
96
|
+
{% endpartialdef main %}
|
|
97
|
+
</body>
|
|
98
|
+
</html>
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
For HTMX requests, `HtmxPartialTemplateMiddleware` rewrites template names to `template.html#partial_name`.
|
|
102
|
+
|
|
103
|
+
Partial resolution follows this order:
|
|
104
|
+
|
|
105
|
+
1. `HX-Retarget`
|
|
106
|
+
2. `HX-Partial-Name`
|
|
107
|
+
3. `request.htmx.target`
|
|
108
|
+
4. `DEFAULT_PARTIAL_NAME` setting, which defaults to `"main"`
|
|
109
|
+
|
|
110
|
+
## Request conventions
|
|
111
|
+
|
|
112
|
+
`HttpVerbViewMiddleware` adds two request attributes:
|
|
113
|
+
|
|
114
|
+
- `request.QUERY`: URL parameters as a `QueryDict`
|
|
115
|
+
- `request.BODY`: request body data as a `QueryDict`
|
|
116
|
+
|
|
117
|
+
For `PUT` and `PATCH`, the middleware supports:
|
|
118
|
+
|
|
119
|
+
- `application/x-www-form-urlencoded`
|
|
120
|
+
- `multipart/form-data`
|
|
121
|
+
|
|
122
|
+
This makes it possible for form-oriented CBVs to treat non-POST verbs more like normal Django form submissions.
|
|
123
|
+
|
|
124
|
+
## View conventions
|
|
125
|
+
|
|
126
|
+
The library is intentionally opinionated.
|
|
127
|
+
|
|
128
|
+
- Plain `TemplateView`, `DetailView`, and `ListView` already work with the middleware in this package.
|
|
129
|
+
Use Django's stock render-only CBVs unless the view itself needs HTMX-aware response logic.
|
|
130
|
+
- `HtmxTemplateResponseMixin` is the reusable view-level abstraction for custom CBVs that want to render inline for HTMX requests.
|
|
131
|
+
- HTMX form success responses render the normal template response instead of redirecting.
|
|
132
|
+
- HTMX form error responses retarget to `#<request.htmx.trigger>`,
|
|
133
|
+
so requests are expected to come from a form element with a stable HTML id.
|
|
134
|
+
- `PATCH` many-to-many updates are additive and use `.add(...)` semantics rather than replacement via `.set(...)`.
|
|
135
|
+
- `ModelFormView.delete()` only uses URL parameters for relationship deletion.
|
|
136
|
+
|
|
137
|
+
## Choosing between the middleware and mixins
|
|
138
|
+
|
|
139
|
+
Use plain Django CBVs when the view just renders a normal template response and HTMX only changes which partial is returned.
|
|
140
|
+
|
|
141
|
+
Use `HtmxTemplateResponseMixin` when the view itself needs to decide how to finalize a response for HTMX requests.
|
|
142
|
+
|
|
143
|
+
Use `HtmxFormMixin` when the view is form-oriented and should keep form-specific HTMX behavior like inline success rendering and error retargeting.
|
|
144
|
+
|
|
145
|
+
Use `HyperFormView` or `ModelFormView` when you want a full HTMX-aware form view with the above behavior and some opinionated defaults.
|
|
146
|
+
|
|
147
|
+
## Example imports
|
|
148
|
+
|
|
149
|
+
```py
|
|
150
|
+
from django_htmx_cbv.views import (
|
|
151
|
+
HtmxFormMixin,
|
|
152
|
+
HtmxTemplateResponseMixin,
|
|
153
|
+
HyperFormView,
|
|
154
|
+
ModelFormView,
|
|
155
|
+
ProcessHyperFormView,
|
|
156
|
+
)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Status
|
|
160
|
+
|
|
161
|
+
This package is still evolving.
|
|
162
|
+
The current API is centered on reusable HTMX behavior for Django CBVs, with explicit middleware and template conventions.
|
|
163
|
+
I welcome input from the community on the API design and implementation;
|
|
164
|
+
I want this to be something we can all use!
|
|
165
|
+
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# Django Class Based Views for HTMX
|
|
2
|
+
|
|
3
|
+
[](https://codecov.io/gh/geoffrey-eisenbarth/django-htmx-cbv)
|
|
4
|
+
|
|
5
|
+
`django-htmx-cbv` provides HTMX-friendly mixins and views for common Django class-based view workflows.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- Python 3.14+
|
|
10
|
+
- Django 6.0+
|
|
11
|
+
- django-htmx
|
|
12
|
+
|
|
13
|
+
This package assumes Django 6.0 template partial support.
|
|
14
|
+
It does not require `django-template-partials`.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
Install the package and `django-htmx`:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install django-htmx-cbv django-htmx
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Or with Poetry:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
poetry add django-htmx-cbv django-htmx
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Django setup
|
|
31
|
+
|
|
32
|
+
Add the app to `INSTALLED_APPS`:
|
|
33
|
+
|
|
34
|
+
```py
|
|
35
|
+
INSTALLED_APPS = [
|
|
36
|
+
# ...
|
|
37
|
+
"django_htmx_cbv",
|
|
38
|
+
]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Add middleware in this order:
|
|
42
|
+
|
|
43
|
+
```py
|
|
44
|
+
MIDDLEWARE = [
|
|
45
|
+
# Django middleware...
|
|
46
|
+
|
|
47
|
+
"django_htmx.middleware.HtmxMiddleware",
|
|
48
|
+
"django_htmx_cbv.middleware.HtmxPartialTemplateMiddleware",
|
|
49
|
+
"django_htmx_cbv.middleware.HtmxVaryMiddleware",
|
|
50
|
+
"django_htmx_cbv.middleware.HtmxMessageMiddleware",
|
|
51
|
+
"django_htmx_cbv.middleware.HttpVerbViewMiddleware",
|
|
52
|
+
|
|
53
|
+
# Other middleware...
|
|
54
|
+
]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Notes:
|
|
58
|
+
|
|
59
|
+
- `django_htmx.middleware.HtmxMiddleware` must run before the `django_htmx_cbv` middleware.
|
|
60
|
+
- `HtmxMessageMiddleware` must come after Django's `MessageMiddleware`.
|
|
61
|
+
- `HttpVerbViewMiddleware` should come after Django's `CsrfViewMiddleware`.
|
|
62
|
+
|
|
63
|
+
The package registers a Django system check for the `HtmxMiddleware` dependency/order.
|
|
64
|
+
|
|
65
|
+
## Template partials
|
|
66
|
+
|
|
67
|
+
This library expects Django 6.0 partial syntax:
|
|
68
|
+
|
|
69
|
+
```django
|
|
70
|
+
<!doctype html>
|
|
71
|
+
<html lang="en">
|
|
72
|
+
<body>
|
|
73
|
+
{% include "messages.html" %}
|
|
74
|
+
{% partialdef main %}
|
|
75
|
+
<main>
|
|
76
|
+
<h1>Example</h1>
|
|
77
|
+
{% partialdef content %}
|
|
78
|
+
<div id="content">Hello</div>
|
|
79
|
+
{% endpartialdef content %}
|
|
80
|
+
</main>
|
|
81
|
+
{% endpartialdef main %}
|
|
82
|
+
</body>
|
|
83
|
+
</html>
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
For HTMX requests, `HtmxPartialTemplateMiddleware` rewrites template names to `template.html#partial_name`.
|
|
87
|
+
|
|
88
|
+
Partial resolution follows this order:
|
|
89
|
+
|
|
90
|
+
1. `HX-Retarget`
|
|
91
|
+
2. `HX-Partial-Name`
|
|
92
|
+
3. `request.htmx.target`
|
|
93
|
+
4. `DEFAULT_PARTIAL_NAME` setting, which defaults to `"main"`
|
|
94
|
+
|
|
95
|
+
## Request conventions
|
|
96
|
+
|
|
97
|
+
`HttpVerbViewMiddleware` adds two request attributes:
|
|
98
|
+
|
|
99
|
+
- `request.QUERY`: URL parameters as a `QueryDict`
|
|
100
|
+
- `request.BODY`: request body data as a `QueryDict`
|
|
101
|
+
|
|
102
|
+
For `PUT` and `PATCH`, the middleware supports:
|
|
103
|
+
|
|
104
|
+
- `application/x-www-form-urlencoded`
|
|
105
|
+
- `multipart/form-data`
|
|
106
|
+
|
|
107
|
+
This makes it possible for form-oriented CBVs to treat non-POST verbs more like normal Django form submissions.
|
|
108
|
+
|
|
109
|
+
## View conventions
|
|
110
|
+
|
|
111
|
+
The library is intentionally opinionated.
|
|
112
|
+
|
|
113
|
+
- Plain `TemplateView`, `DetailView`, and `ListView` already work with the middleware in this package.
|
|
114
|
+
Use Django's stock render-only CBVs unless the view itself needs HTMX-aware response logic.
|
|
115
|
+
- `HtmxTemplateResponseMixin` is the reusable view-level abstraction for custom CBVs that want to render inline for HTMX requests.
|
|
116
|
+
- HTMX form success responses render the normal template response instead of redirecting.
|
|
117
|
+
- HTMX form error responses retarget to `#<request.htmx.trigger>`,
|
|
118
|
+
so requests are expected to come from a form element with a stable HTML id.
|
|
119
|
+
- `PATCH` many-to-many updates are additive and use `.add(...)` semantics rather than replacement via `.set(...)`.
|
|
120
|
+
- `ModelFormView.delete()` only uses URL parameters for relationship deletion.
|
|
121
|
+
|
|
122
|
+
## Choosing between the middleware and mixins
|
|
123
|
+
|
|
124
|
+
Use plain Django CBVs when the view just renders a normal template response and HTMX only changes which partial is returned.
|
|
125
|
+
|
|
126
|
+
Use `HtmxTemplateResponseMixin` when the view itself needs to decide how to finalize a response for HTMX requests.
|
|
127
|
+
|
|
128
|
+
Use `HtmxFormMixin` when the view is form-oriented and should keep form-specific HTMX behavior like inline success rendering and error retargeting.
|
|
129
|
+
|
|
130
|
+
Use `HyperFormView` or `ModelFormView` when you want a full HTMX-aware form view with the above behavior and some opinionated defaults.
|
|
131
|
+
|
|
132
|
+
## Example imports
|
|
133
|
+
|
|
134
|
+
```py
|
|
135
|
+
from django_htmx_cbv.views import (
|
|
136
|
+
HtmxFormMixin,
|
|
137
|
+
HtmxTemplateResponseMixin,
|
|
138
|
+
HyperFormView,
|
|
139
|
+
ModelFormView,
|
|
140
|
+
ProcessHyperFormView,
|
|
141
|
+
)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Status
|
|
145
|
+
|
|
146
|
+
This package is still evolving.
|
|
147
|
+
The current API is centered on reusable HTMX behavior for Django CBVs, with explicit middleware and template conventions.
|
|
148
|
+
I welcome input from the community on the API design and implementation;
|
|
149
|
+
I want this to be something we can all use!
|
|
File without changes
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
3
|
+
from django.conf import settings
|
|
4
|
+
from django.core.checks import Error, register
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from collections.abc import Iterable, Sequence
|
|
9
|
+
from typing import Any
|
|
10
|
+
from django.apps import AppConfig
|
|
11
|
+
from django.core.checks import CheckMessage
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
HTMX_MIDDLEWARE = 'django_htmx.middleware.HtmxMiddleware'
|
|
15
|
+
CBV_MIDDLEWARE_PREFIX = 'django_htmx_cbv.middleware.'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@register()
|
|
19
|
+
def check_htmx_middleware_order(
|
|
20
|
+
*,
|
|
21
|
+
app_configs: Sequence[AppConfig] | None,
|
|
22
|
+
databases: Sequence[str] | None = None,
|
|
23
|
+
**kwargs: Any,
|
|
24
|
+
) -> Iterable[CheckMessage]:
|
|
25
|
+
middleware = list(getattr(settings, 'MIDDLEWARE', []))
|
|
26
|
+
cbv_indices = [
|
|
27
|
+
index
|
|
28
|
+
for index, path in enumerate(middleware)
|
|
29
|
+
if path.startswith(CBV_MIDDLEWARE_PREFIX)
|
|
30
|
+
]
|
|
31
|
+
if not cbv_indices:
|
|
32
|
+
return []
|
|
33
|
+
|
|
34
|
+
if HTMX_MIDDLEWARE not in middleware:
|
|
35
|
+
return [
|
|
36
|
+
Error(
|
|
37
|
+
"django-htmx middleware is required by django-htmx-cbv middleware.",
|
|
38
|
+
hint=(
|
|
39
|
+
"Add 'django_htmx.middleware.HtmxMiddleware' before any "
|
|
40
|
+
"'django_htmx_cbv.middleware.*' entries in MIDDLEWARE."
|
|
41
|
+
),
|
|
42
|
+
id='django_htmx_cbv.E001',
|
|
43
|
+
)
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
htmx_index = middleware.index(HTMX_MIDDLEWARE)
|
|
47
|
+
if any(index < htmx_index for index in cbv_indices):
|
|
48
|
+
return [
|
|
49
|
+
Error(
|
|
50
|
+
"django-htmx middleware must run before django-htmx-cbv middleware.",
|
|
51
|
+
hint=(
|
|
52
|
+
"Move 'django_htmx.middleware.HtmxMiddleware' above all "
|
|
53
|
+
"'django_htmx_cbv.middleware.*' entries in MIDDLEWARE."
|
|
54
|
+
),
|
|
55
|
+
id='django_htmx_cbv.E002',
|
|
56
|
+
)
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
return []
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
3
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
4
|
+
from django.db.models import QuerySet
|
|
5
|
+
from django.forms import Form
|
|
6
|
+
from django.http import HttpResponse
|
|
7
|
+
from django.utils.translation import gettext_lazy as _
|
|
8
|
+
|
|
9
|
+
from django_htmx_cbv.views import ProcessHyperFormView
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from typing import Any
|
|
14
|
+
from django import forms
|
|
15
|
+
from django.http import HttpRequest
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# forms.py
|
|
19
|
+
class HtmxChainedForm(Form):
|
|
20
|
+
"""Custom form subclass to work with HtmxChainedFormView."""
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
options: dict[str, Any] | None = None,
|
|
24
|
+
*args: Any,
|
|
25
|
+
**kwargs: Any,
|
|
26
|
+
) -> None:
|
|
27
|
+
super().__init__(*args, **kwargs)
|
|
28
|
+
|
|
29
|
+
# Set options on form
|
|
30
|
+
if options is not None:
|
|
31
|
+
for field_name, choices in options.items():
|
|
32
|
+
form_field = self.fields[field_name]
|
|
33
|
+
if hasattr(form_field, 'queryset'):
|
|
34
|
+
if isinstance(choices, QuerySet):
|
|
35
|
+
form_field.queryset = choices
|
|
36
|
+
else:
|
|
37
|
+
message = _(
|
|
38
|
+
f'The choices for {field_name} must be a QuerySet!'
|
|
39
|
+
)
|
|
40
|
+
raise TypeError(message)
|
|
41
|
+
elif hasattr(form_field, 'choices'):
|
|
42
|
+
if isinstance(choices, list):
|
|
43
|
+
form_field.choices = choices
|
|
44
|
+
else:
|
|
45
|
+
message = _(
|
|
46
|
+
f'The choices for {field_name} must be a list of tuples!'
|
|
47
|
+
)
|
|
48
|
+
raise TypeError(message)
|
|
49
|
+
self.fields[field_name] = form_field
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# views.py
|
|
53
|
+
class HtmxChainedFormView[_F: forms.BaseForm](ProcessHyperFormView[_F]):
|
|
54
|
+
"""Allows dynamic chained form fields."""
|
|
55
|
+
|
|
56
|
+
def get_options(self) -> dict[str, Any]:
|
|
57
|
+
message = (
|
|
58
|
+
"HtmxChainedFormView requires an implementation "
|
|
59
|
+
"of `get_options()` that returns a dictionary "
|
|
60
|
+
"of the form {field_name: [choices]}. If form "
|
|
61
|
+
"values are required, they should be specified "
|
|
62
|
+
"via `hx-include`."
|
|
63
|
+
)
|
|
64
|
+
raise ImproperlyConfigured(message)
|
|
65
|
+
|
|
66
|
+
def get_form_kwargs(self) -> dict[str, Any]:
|
|
67
|
+
"""Override to provide `options` kwarg.
|
|
68
|
+
|
|
69
|
+
Notes
|
|
70
|
+
-----
|
|
71
|
+
Django Form instances that are going to be used with this view must
|
|
72
|
+
allow a `options` kwarg in their __init__ method.
|
|
73
|
+
|
|
74
|
+
"""
|
|
75
|
+
kwargs = super().get_form_kwargs()
|
|
76
|
+
if self.request.htmx:
|
|
77
|
+
kwargs['options'] = self.get_options()
|
|
78
|
+
return kwargs
|
|
79
|
+
|
|
80
|
+
def get(
|
|
81
|
+
self,
|
|
82
|
+
request: HttpRequest,
|
|
83
|
+
*args: Any,
|
|
84
|
+
**kwargs: Any,
|
|
85
|
+
) -> HttpResponse:
|
|
86
|
+
"""Override to determine what needs to be rendered."""
|
|
87
|
+
# TODO PUSH: Find a proper way to get field ids? (See 'id_' below too)
|
|
88
|
+
form_class = self.get_form_class()
|
|
89
|
+
form_field_ids = [
|
|
90
|
+
f'id_{field_name}'
|
|
91
|
+
for field_name, field in form_class.base_fields.items()
|
|
92
|
+
if hasattr(field, 'choices')
|
|
93
|
+
] + ['id_choices']
|
|
94
|
+
|
|
95
|
+
if request.htmx.target in form_field_ids:
|
|
96
|
+
form_class = self.get_form_class()
|
|
97
|
+
kwargs = self.get_form_kwargs()
|
|
98
|
+
form = form_class(**kwargs)
|
|
99
|
+
|
|
100
|
+
html = "".join(
|
|
101
|
+
map(str, (form[field_name] for field_name in kwargs['options']))
|
|
102
|
+
)
|
|
103
|
+
response = HttpResponse(html)
|
|
104
|
+
else:
|
|
105
|
+
response = HttpResponse(status=204)
|
|
106
|
+
|
|
107
|
+
return response
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, cast
|
|
2
|
+
|
|
3
|
+
from django.conf import settings
|
|
4
|
+
from django.contrib.messages import get_messages
|
|
5
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
6
|
+
from django.http import HttpResponse, QueryDict
|
|
7
|
+
from django.http.multipartparser import MultiPartParserError
|
|
8
|
+
from django.template.loader import render_to_string
|
|
9
|
+
from django.http.response import HttpResponseRedirectBase
|
|
10
|
+
from django.utils.cache import patch_vary_headers
|
|
11
|
+
|
|
12
|
+
from django_htmx.http import HttpResponseClientRedirect
|
|
13
|
+
from django_htmx.middleware import HtmxDetails
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from typing import Any, Callable, Protocol, Sequence
|
|
18
|
+
from django.http import HttpRequest
|
|
19
|
+
from django.template.response import SimpleTemplateResponse
|
|
20
|
+
|
|
21
|
+
class HtmxRequest(Protocol):
|
|
22
|
+
htmx: HtmxDetails
|
|
23
|
+
QUERY: QueryDict
|
|
24
|
+
BODY: QueryDict
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _get_htmx_request(request: 'HttpRequest') -> 'HtmxRequest':
|
|
28
|
+
if not isinstance(getattr(request, 'htmx', None), HtmxDetails):
|
|
29
|
+
message = (
|
|
30
|
+
"django_htmx.middleware.HtmxMiddleware must be installed and run "
|
|
31
|
+
"before django_htmx_cbv middleware."
|
|
32
|
+
)
|
|
33
|
+
raise ImproperlyConfigured(message)
|
|
34
|
+
return cast('HtmxRequest', request)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# TODO: PUSH: Make sure CSRF Protection is enabled for hx-put, patch, delete
|
|
38
|
+
# TODO: Add note to README about keeping HTMX default for DELETE
|
|
39
|
+
# https://github.com/bigskysoftware/htmx/issues/497#issuecomment-2406237261
|
|
40
|
+
class HtmxVaryMiddleware:
|
|
41
|
+
"""Sets the 'Vary' header to avoid improper caching.
|
|
42
|
+
|
|
43
|
+
Notes
|
|
44
|
+
-----
|
|
45
|
+
See https://htmx.org/docs/#caching
|
|
46
|
+
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
get_response: Callable[[HttpRequest], HttpResponse],
|
|
52
|
+
) -> None:
|
|
53
|
+
self.get_response = get_response
|
|
54
|
+
|
|
55
|
+
def __call__(self, request: HttpRequest) -> HttpResponse:
|
|
56
|
+
response = self.get_response(request)
|
|
57
|
+
htmx_request = _get_htmx_request(request)
|
|
58
|
+
if htmx_request.htmx:
|
|
59
|
+
patch_vary_headers(response, ['HX-Request'])
|
|
60
|
+
return response
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# TODO PUSH: Do we need CSRF Protection for hx-put, hx-patch, and hx-delete
|
|
64
|
+
class HttpVerbViewMiddleware:
|
|
65
|
+
"""Adds support for all HTTP verbs.
|
|
66
|
+
|
|
67
|
+
Notes
|
|
68
|
+
-----
|
|
69
|
+
Django uses request.GET and request.POST to store QueryDicts
|
|
70
|
+
of the request's URL parameters and body respectively. In an
|
|
71
|
+
attempt to more accurately depict their roles, we store these
|
|
72
|
+
values in request.QUERY and request.BODY.
|
|
73
|
+
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(
|
|
77
|
+
self,
|
|
78
|
+
get_response: Callable[[HttpRequest], HttpResponse],
|
|
79
|
+
) -> None:
|
|
80
|
+
self.get_response = get_response
|
|
81
|
+
|
|
82
|
+
def __call__(self, request: HttpRequest) -> HttpResponse:
|
|
83
|
+
return self.get_response(request)
|
|
84
|
+
|
|
85
|
+
def process_view(
|
|
86
|
+
self,
|
|
87
|
+
request: HttpRequest,
|
|
88
|
+
view_func: Callable[[HttpRequest], HttpResponse],
|
|
89
|
+
view_args: Any,
|
|
90
|
+
view_kwargs: Any,
|
|
91
|
+
) -> None:
|
|
92
|
+
htmx_request = _get_htmx_request(request)
|
|
93
|
+
htmx_request.QUERY = request.GET.copy()
|
|
94
|
+
htmx_request.BODY = QueryDict()
|
|
95
|
+
|
|
96
|
+
if request.method in ['GET', 'DELETE']:
|
|
97
|
+
pass
|
|
98
|
+
elif request.method == 'POST':
|
|
99
|
+
htmx_request.BODY = request.POST.copy()
|
|
100
|
+
elif request.method in ['PUT', 'PATCH']:
|
|
101
|
+
if request.content_type == 'application/x-www-form-urlencoded':
|
|
102
|
+
htmx_request.BODY = QueryDict(request.body)
|
|
103
|
+
elif request.content_type == 'multipart/form-data':
|
|
104
|
+
try:
|
|
105
|
+
body, files = request.parse_file_upload(request.META, request)
|
|
106
|
+
except MultiPartParserError as exc:
|
|
107
|
+
raise ImproperlyConfigured(str(exc)) from exc
|
|
108
|
+
htmx_request.BODY = body.copy()
|
|
109
|
+
cast('Any', request)._post = body
|
|
110
|
+
cast('Any', request)._files = files
|
|
111
|
+
|
|
112
|
+
if not htmx_request.htmx:
|
|
113
|
+
if _method := (
|
|
114
|
+
htmx_request.BODY.get('_method')
|
|
115
|
+
or htmx_request.QUERY.get('_method')
|
|
116
|
+
):
|
|
117
|
+
request.method = _method.upper()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class HtmxPartialTemplateMiddleware:
|
|
121
|
+
"""Adds support for rendering partials."""
|
|
122
|
+
|
|
123
|
+
default_partial_name = getattr(
|
|
124
|
+
settings,
|
|
125
|
+
'DEFAULT_PARTIAL_NAME',
|
|
126
|
+
'main',
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def __init__(
|
|
130
|
+
self,
|
|
131
|
+
get_response: Callable[[HttpRequest], HttpResponse],
|
|
132
|
+
) -> None:
|
|
133
|
+
self.get_response = get_response
|
|
134
|
+
|
|
135
|
+
def __call__(self, request: HttpRequest) -> HttpResponse:
|
|
136
|
+
response = self.get_response(request)
|
|
137
|
+
htmx_request = _get_htmx_request(request)
|
|
138
|
+
if htmx_request.htmx and isinstance(response, HttpResponseRedirectBase):
|
|
139
|
+
response = HttpResponseClientRedirect(response.url)
|
|
140
|
+
return response
|
|
141
|
+
|
|
142
|
+
def process_template_response(
|
|
143
|
+
self,
|
|
144
|
+
request: HttpRequest,
|
|
145
|
+
response: SimpleTemplateResponse,
|
|
146
|
+
) -> SimpleTemplateResponse:
|
|
147
|
+
htmx_request = _get_htmx_request(request)
|
|
148
|
+
if htmx_request.htmx:
|
|
149
|
+
if retarget_id := response.get('HX-Retarget'):
|
|
150
|
+
partial_name = retarget_id.strip('#')
|
|
151
|
+
elif partial_name := response.get('HX-Partial-Name', ''):
|
|
152
|
+
# Allow the view to specify the partial name
|
|
153
|
+
pass
|
|
154
|
+
else:
|
|
155
|
+
partial_name = htmx_request.htmx.target or self.default_partial_name
|
|
156
|
+
|
|
157
|
+
template_name = response.template_name
|
|
158
|
+
if template_name is None:
|
|
159
|
+
return response
|
|
160
|
+
if isinstance(template_name, str):
|
|
161
|
+
template_names = [template_name]
|
|
162
|
+
else:
|
|
163
|
+
template_names = list(cast('Sequence[str]', template_name))
|
|
164
|
+
|
|
165
|
+
response.template_name = [
|
|
166
|
+
f'{name}#{partial_name}'
|
|
167
|
+
if '#' not in name
|
|
168
|
+
else name
|
|
169
|
+
for name in template_names
|
|
170
|
+
]
|
|
171
|
+
return response
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# https://github.com/bblanchon/django-htmx-messages-framework/
|
|
175
|
+
# https://github.com/abe-101/django-htmx-messages
|
|
176
|
+
class HtmxMessageMiddleware:
|
|
177
|
+
"""Middleware to add HTMX support to messages framework.
|
|
178
|
+
|
|
179
|
+
Notes
|
|
180
|
+
-----
|
|
181
|
+
This code comes from Benoit Blanchon:
|
|
182
|
+
https://github.com/bblanchon/django-htmx-messages-framework/tree/oob
|
|
183
|
+
|
|
184
|
+
This come come AFTER django.contrib.messages.middleware.MessageMiddleware
|
|
185
|
+
in the setting's MIDDLEWARE list!
|
|
186
|
+
|
|
187
|
+
Since our <output#messages/> element is not located in the <main/> element,
|
|
188
|
+
where most HTMX partials are swapped, we must render the messages.html
|
|
189
|
+
template for every response, in order to "clear out" old messages via an
|
|
190
|
+
OOB swap. It would be more efficient to include the <output#messages/>
|
|
191
|
+
element inside the normal HX-Target area, however this would require
|
|
192
|
+
something like {% include 'messages.html' %} in every template, unless
|
|
193
|
+
we changed the django-render-block logic.
|
|
194
|
+
|
|
195
|
+
"""
|
|
196
|
+
|
|
197
|
+
messages_template = getattr(
|
|
198
|
+
settings,
|
|
199
|
+
'MESSAGES_TEMPLATE_NAME',
|
|
200
|
+
'messages.html',
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def __init__(
|
|
204
|
+
self,
|
|
205
|
+
get_response: Callable[[HttpRequest], HttpResponse],
|
|
206
|
+
) -> None:
|
|
207
|
+
self.get_response = get_response
|
|
208
|
+
|
|
209
|
+
def __call__(self, request: HttpRequest) -> HttpResponse:
|
|
210
|
+
|
|
211
|
+
response = self.get_response(request)
|
|
212
|
+
|
|
213
|
+
if 'HX-Request' not in request.headers:
|
|
214
|
+
# Not an HTMX request, so full page rendering will pick up the message
|
|
215
|
+
return response
|
|
216
|
+
elif 300 <= response.status_code < 400:
|
|
217
|
+
# Ignore redirections because HTMX cannot read the body
|
|
218
|
+
return response
|
|
219
|
+
elif 'HX-Redirect' in response.headers:
|
|
220
|
+
# Ignore client-side redirection because HTMX drops OOB swabs
|
|
221
|
+
return response
|
|
222
|
+
|
|
223
|
+
# Add message HTML
|
|
224
|
+
if messages := get_messages(request):
|
|
225
|
+
html = render_to_string(
|
|
226
|
+
template_name=self.messages_template,
|
|
227
|
+
context={'messages': messages},
|
|
228
|
+
request=request,
|
|
229
|
+
)
|
|
230
|
+
if response.status_code == 204:
|
|
231
|
+
# 204: No Content, so replace with a contentful response
|
|
232
|
+
response = HttpResponse(html, status=200)
|
|
233
|
+
else:
|
|
234
|
+
# Write the OOB swap into the response
|
|
235
|
+
response.write(html)
|
|
236
|
+
return response
|
|
File without changes
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, cast
|
|
2
|
+
|
|
3
|
+
from django.contrib import messages
|
|
4
|
+
from django.contrib.messages.views import SuccessMessageMixin
|
|
5
|
+
from django.core.exceptions import (
|
|
6
|
+
ImproperlyConfigured, PermissionDenied, BadRequest,
|
|
7
|
+
)
|
|
8
|
+
from django.http import HttpResponse, HttpResponseRedirect
|
|
9
|
+
from django.views.generic.base import TemplateResponseMixin, View
|
|
10
|
+
from django.views.generic.detail import SingleObjectMixin
|
|
11
|
+
from django.views.generic.edit import FormMixin, ModelFormMixin
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from typing import Any, Protocol, Sequence
|
|
17
|
+
from django import forms
|
|
18
|
+
from django.db.models import Model
|
|
19
|
+
from django.http import HttpRequest, QueryDict
|
|
20
|
+
from django_htmx.middleware import HtmxDetails
|
|
21
|
+
|
|
22
|
+
class HtmxRequest(Protocol):
|
|
23
|
+
htmx: HtmxDetails
|
|
24
|
+
method: str
|
|
25
|
+
FILES: Any
|
|
26
|
+
QUERY: QueryDict
|
|
27
|
+
BODY: QueryDict
|
|
28
|
+
|
|
29
|
+
class FormClassWithBaseFields[_F: forms.BaseForm](Protocol):
|
|
30
|
+
base_fields: Mapping[str, object]
|
|
31
|
+
|
|
32
|
+
def __call__(
|
|
33
|
+
self,
|
|
34
|
+
*args: Any,
|
|
35
|
+
**kwargs: Any,
|
|
36
|
+
) -> _F:
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
class SupportsSetup(Protocol):
|
|
40
|
+
def setup(
|
|
41
|
+
self,
|
|
42
|
+
request: HttpRequest,
|
|
43
|
+
*args: Any,
|
|
44
|
+
**kwargs: Any,
|
|
45
|
+
) -> None:
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
class SupportsContextData(Protocol):
|
|
49
|
+
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class HtmxTemplateResponseMixin(TemplateResponseMixin):
|
|
54
|
+
"""Render template responses inline for HTMX requests."""
|
|
55
|
+
|
|
56
|
+
def _finalize_htmx_response(
|
|
57
|
+
self,
|
|
58
|
+
response: HttpResponse,
|
|
59
|
+
**context: 'Any',
|
|
60
|
+
) -> HttpResponse:
|
|
61
|
+
request = cast('HtmxRequest', self.request)
|
|
62
|
+
if request.htmx:
|
|
63
|
+
context_mixin = cast('SupportsContextData', self)
|
|
64
|
+
rendered_context = context_mixin.get_context_data(**context)
|
|
65
|
+
response = self.render_to_response(rendered_context)
|
|
66
|
+
return response
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class HtmxFormMixin[_F: forms.BaseForm](
|
|
70
|
+
HtmxTemplateResponseMixin,
|
|
71
|
+
FormMixin[_F],
|
|
72
|
+
):
|
|
73
|
+
"""Mixin for facilitating HTMX submission of forms.
|
|
74
|
+
|
|
75
|
+
Notes
|
|
76
|
+
-----
|
|
77
|
+
This mixin should come before any other form related mixins/views.
|
|
78
|
+
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def form_valid(self, form: _F) -> HttpResponse:
|
|
82
|
+
"""The POST/Redirect/GET pattern is not necessary with HTMX.
|
|
83
|
+
|
|
84
|
+
Notes
|
|
85
|
+
-----
|
|
86
|
+
In order to prevent extra db queries, we must pass the `form`
|
|
87
|
+
to `get_context_data()`, otherwise Django's FormMixin will
|
|
88
|
+
call `get_form()` a second time.
|
|
89
|
+
"""
|
|
90
|
+
response = super().form_valid(form)
|
|
91
|
+
return self._finalize_htmx_response(response, form=form)
|
|
92
|
+
|
|
93
|
+
def form_invalid(self, form: _F) -> HttpResponse:
|
|
94
|
+
"""Retarget form errors."""
|
|
95
|
+
response = super().form_invalid(form)
|
|
96
|
+
request = cast('HtmxRequest', self.request)
|
|
97
|
+
|
|
98
|
+
if request.htmx:
|
|
99
|
+
if request.htmx.trigger is None:
|
|
100
|
+
message = (
|
|
101
|
+
"HtmxFormMixin requires that requests are triggered by a form "
|
|
102
|
+
"with an HTML id and matching partial block name."
|
|
103
|
+
)
|
|
104
|
+
raise ImproperlyConfigured(message)
|
|
105
|
+
response['HX-Retarget'] = f'#{request.htmx.trigger}'
|
|
106
|
+
response['HX-Reswap'] = 'outerHTML'
|
|
107
|
+
return response
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class HyperFormMixin[_F: forms.BaseForm](HtmxFormMixin[_F]):
|
|
111
|
+
"""Add support for all HTTP Verbs to Django's FormMixin."""
|
|
112
|
+
|
|
113
|
+
http_method_names: Sequence[str] = ('get', 'post', 'put', 'patch', 'delete')
|
|
114
|
+
|
|
115
|
+
def get_initial(self) -> dict[str, Any]:
|
|
116
|
+
initial = super().get_initial()
|
|
117
|
+
|
|
118
|
+
assert self.form_class is not None
|
|
119
|
+
request = cast('HtmxRequest', self.request)
|
|
120
|
+
form_class = cast('FormClassWithBaseFields[_F]', self.form_class)
|
|
121
|
+
|
|
122
|
+
form_method = getattr(form_class, 'method', '').upper()
|
|
123
|
+
# TODO: Or if self.http_method_names != ['get']?
|
|
124
|
+
if form_method != 'GET' and request.QUERY:
|
|
125
|
+
# Pass relevant URL params to the form as initial values
|
|
126
|
+
initial.update({
|
|
127
|
+
key: value
|
|
128
|
+
for key, value in request.QUERY.dict().items()
|
|
129
|
+
if key in form_class.base_fields
|
|
130
|
+
})
|
|
131
|
+
return initial
|
|
132
|
+
|
|
133
|
+
def get_form_kwargs(self) -> dict[str, Any]:
|
|
134
|
+
"""Allow all HTTP verbs and facilitate GET forms.
|
|
135
|
+
|
|
136
|
+
Notes
|
|
137
|
+
-----
|
|
138
|
+
In the case of GET forms, it's imperative that we set the `data` form kwarg
|
|
139
|
+
to `self.get_initial()` in order to actually bind the initial data to the
|
|
140
|
+
form and get a proper response. Otherwise, initial data is simply for
|
|
141
|
+
presentation and will not contribute towards satisfying `form.is_valid()`.
|
|
142
|
+
However, if data is submitted we want that to take precedence over
|
|
143
|
+
`self.get_initial()`.
|
|
144
|
+
|
|
145
|
+
"""
|
|
146
|
+
request = cast('HtmxRequest', self.request)
|
|
147
|
+
|
|
148
|
+
kwargs = super().get_form_kwargs()
|
|
149
|
+
# TODO: or if self.http_method_names == ['get']?
|
|
150
|
+
if getattr(self.form_class, 'method', '').upper() == 'GET':
|
|
151
|
+
if data := (request.QUERY or kwargs.get('initial')):
|
|
152
|
+
kwargs.update({
|
|
153
|
+
'data': data,
|
|
154
|
+
'files': request.FILES,
|
|
155
|
+
})
|
|
156
|
+
else:
|
|
157
|
+
# Must avoid binding the form by passing an empty dict to `data`
|
|
158
|
+
pass
|
|
159
|
+
elif request.method != 'GET':
|
|
160
|
+
kwargs.update({
|
|
161
|
+
'data': request.BODY,
|
|
162
|
+
'files': request.FILES,
|
|
163
|
+
})
|
|
164
|
+
return kwargs
|
|
165
|
+
|
|
166
|
+
def form_valid(self, form: _F) -> HttpResponse:
|
|
167
|
+
"""Proper response handling per HTTP verb."""
|
|
168
|
+
if self.request.method == 'GET':
|
|
169
|
+
message = (
|
|
170
|
+
"Views that inherit from HyperFormMixin must implement "
|
|
171
|
+
"a custom `form_valid()` for forms with [method=get]."
|
|
172
|
+
)
|
|
173
|
+
raise ImproperlyConfigured(message)
|
|
174
|
+
return super().form_valid(form)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class ProcessHyperFormView[_F: forms.BaseForm](HyperFormMixin[_F], View):
|
|
178
|
+
"""Render a form on GET and facilitate processing on any verb."""
|
|
179
|
+
|
|
180
|
+
def get(
|
|
181
|
+
self,
|
|
182
|
+
request: HttpRequest,
|
|
183
|
+
*args: Any,
|
|
184
|
+
**kwargs: Any,
|
|
185
|
+
) -> HttpResponse:
|
|
186
|
+
form = self.get_form()
|
|
187
|
+
if form.is_valid():
|
|
188
|
+
response = self.form_valid(form)
|
|
189
|
+
elif form.is_bound:
|
|
190
|
+
response = self.form_invalid(form)
|
|
191
|
+
else:
|
|
192
|
+
# Render the initial GET
|
|
193
|
+
response = self.render_to_response(self.get_context_data(form=form))
|
|
194
|
+
return response
|
|
195
|
+
|
|
196
|
+
def process_form(
|
|
197
|
+
self,
|
|
198
|
+
request: HttpRequest,
|
|
199
|
+
*args: Any,
|
|
200
|
+
**kwargs: Any,
|
|
201
|
+
) -> HttpResponse:
|
|
202
|
+
form = self.get_form()
|
|
203
|
+
if form.is_valid():
|
|
204
|
+
response = self.form_valid(form)
|
|
205
|
+
else:
|
|
206
|
+
response = self.form_invalid(form)
|
|
207
|
+
return response
|
|
208
|
+
|
|
209
|
+
def post(
|
|
210
|
+
self,
|
|
211
|
+
request: HttpRequest,
|
|
212
|
+
*args: Any,
|
|
213
|
+
**kwargs: Any,
|
|
214
|
+
) -> HttpResponse:
|
|
215
|
+
return self.process_form(request, *args, **kwargs)
|
|
216
|
+
|
|
217
|
+
def put(
|
|
218
|
+
self,
|
|
219
|
+
request: HttpRequest,
|
|
220
|
+
*args: Any,
|
|
221
|
+
**kwargs: Any,
|
|
222
|
+
) -> HttpResponse:
|
|
223
|
+
return self.process_form(request, *args, **kwargs)
|
|
224
|
+
|
|
225
|
+
def patch(
|
|
226
|
+
self,
|
|
227
|
+
request: HttpRequest,
|
|
228
|
+
*args: Any,
|
|
229
|
+
**kwargs: Any,
|
|
230
|
+
) -> HttpResponse:
|
|
231
|
+
return self.process_form(request, *args, **kwargs)
|
|
232
|
+
|
|
233
|
+
def delete(
|
|
234
|
+
self,
|
|
235
|
+
request: HttpRequest,
|
|
236
|
+
*args: Any,
|
|
237
|
+
**kwargs: Any,
|
|
238
|
+
) -> HttpResponse:
|
|
239
|
+
"""No form validation is performed for DELETE requests."""
|
|
240
|
+
message = (
|
|
241
|
+
"ProcessHyperFormView requires that subclasses define their "
|
|
242
|
+
"own `delete()` methods."
|
|
243
|
+
)
|
|
244
|
+
raise ImproperlyConfigured(message)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class HyperFormView[_F: forms.BaseForm](ProcessHyperFormView[_F]):
|
|
248
|
+
"""A view for displaying a form and rendering a template response."""
|
|
249
|
+
pass
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class SingleObjectPermissionMixin[_M: Model](SingleObjectMixin[_M]):
|
|
253
|
+
"""Adds a permisssions check to SingleObjectMixin."""
|
|
254
|
+
|
|
255
|
+
object: _M | None
|
|
256
|
+
|
|
257
|
+
def setup(
|
|
258
|
+
self,
|
|
259
|
+
request: HttpRequest,
|
|
260
|
+
*args: Any,
|
|
261
|
+
**kwargs: Any,
|
|
262
|
+
) -> None:
|
|
263
|
+
cast('SupportsSetup', super()).setup(request, *args, **kwargs)
|
|
264
|
+
if (
|
|
265
|
+
self.pk_url_kwarg in kwargs
|
|
266
|
+
or self.slug_url_kwarg in kwargs
|
|
267
|
+
):
|
|
268
|
+
# Update or delete object
|
|
269
|
+
self.object = self.get_object(*args, **kwargs)
|
|
270
|
+
else:
|
|
271
|
+
# Create object
|
|
272
|
+
self.object = None
|
|
273
|
+
|
|
274
|
+
# Verify the User has CRUD permissions
|
|
275
|
+
if not self.has_permission(request, self.object):
|
|
276
|
+
raise PermissionDenied
|
|
277
|
+
|
|
278
|
+
def has_permission(
|
|
279
|
+
self,
|
|
280
|
+
request: HttpRequest,
|
|
281
|
+
obj: Model | None,
|
|
282
|
+
) -> bool:
|
|
283
|
+
message = (
|
|
284
|
+
"SingleObjectPermissionMixin requires that subclasses define a "
|
|
285
|
+
"`has_permission()` method for determining if the request "
|
|
286
|
+
"is allowed or not."
|
|
287
|
+
)
|
|
288
|
+
raise ImproperlyConfigured(message)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class ModelFormView[_M: Model, _F: forms.ModelForm[Any]](
|
|
292
|
+
SuccessMessageMixin[_F],
|
|
293
|
+
SingleObjectPermissionMixin[_M],
|
|
294
|
+
ModelFormMixin[_M, _F],
|
|
295
|
+
HyperFormView[_F],
|
|
296
|
+
):
|
|
297
|
+
"""Combines Django's CreateView, UpdateView, and DeleteView via HTMX.
|
|
298
|
+
|
|
299
|
+
Notes
|
|
300
|
+
-----
|
|
301
|
+
Generally we use the following convention for mapping HTTP verbs to
|
|
302
|
+
CRUD verbs:
|
|
303
|
+
o POST = CREATE: A new object with this payload
|
|
304
|
+
o GET = READ: All objects or one object
|
|
305
|
+
o PUT = UPDATE: All of an existing object's data
|
|
306
|
+
o PATCH = UPDATE: Some of an exisiting object's data
|
|
307
|
+
o DELETE = DELETE: Delete this object
|
|
308
|
+
|
|
309
|
+
Furthermore, the following verbs are treated as idempotent:
|
|
310
|
+
o GET
|
|
311
|
+
o PUT
|
|
312
|
+
o DELETE
|
|
313
|
+
|
|
314
|
+
"""
|
|
315
|
+
|
|
316
|
+
http_method_names: Sequence[str] = ('get', 'post', 'patch', 'put', 'delete')
|
|
317
|
+
|
|
318
|
+
def form_valid(self, form: _F) -> HttpResponse:
|
|
319
|
+
if self.request.method != 'PATCH':
|
|
320
|
+
return super().form_valid(form)
|
|
321
|
+
|
|
322
|
+
self.object = form.save(commit=False)
|
|
323
|
+
self.object.save()
|
|
324
|
+
|
|
325
|
+
# PATCH should append related objects instead of replacing them with set().
|
|
326
|
+
for field in self.object._meta.many_to_many:
|
|
327
|
+
values = form.cleaned_data.get(field.name)
|
|
328
|
+
if values is not None:
|
|
329
|
+
getattr(self.object, field.name).add(*values)
|
|
330
|
+
|
|
331
|
+
if message := self.get_success_message(form.cleaned_data):
|
|
332
|
+
messages.success(self.request, message)
|
|
333
|
+
|
|
334
|
+
response = HttpResponseRedirect(self.get_success_url())
|
|
335
|
+
return self._finalize_htmx_response(response, form=form)
|
|
336
|
+
|
|
337
|
+
def delete(
|
|
338
|
+
self,
|
|
339
|
+
request: HttpRequest,
|
|
340
|
+
*args: Any,
|
|
341
|
+
**kwargs: Any,
|
|
342
|
+
) -> HttpResponse:
|
|
343
|
+
"""Delete the object or the requested relationships.
|
|
344
|
+
|
|
345
|
+
Notes
|
|
346
|
+
-----
|
|
347
|
+
While DELETE verbs should support both request bodies and URL params,
|
|
348
|
+
we make the opinionated decision to only support URL params.
|
|
349
|
+
|
|
350
|
+
"""
|
|
351
|
+
assert self.object is not None
|
|
352
|
+
htmx_request = cast('HtmxRequest', request)
|
|
353
|
+
|
|
354
|
+
field_names = set(f.name for f in self.object._meta.get_fields())
|
|
355
|
+
param_names = set(htmx_request.QUERY)
|
|
356
|
+
|
|
357
|
+
if (related_names := (field_names & param_names)):
|
|
358
|
+
# Do not delete the primary object, only the related data
|
|
359
|
+
for name in related_names:
|
|
360
|
+
field = self.object._meta.get_field(name)
|
|
361
|
+
if field.many_to_many:
|
|
362
|
+
# Remove from ManyToMany relation, no need to save object afterwards
|
|
363
|
+
getattr(self.object, name).remove(*htmx_request.QUERY.getlist(name))
|
|
364
|
+
elif field.one_to_one or field.many_to_one:
|
|
365
|
+
# ForeignKey or OneToOneField, must save object
|
|
366
|
+
if not field.null:
|
|
367
|
+
raise BadRequest
|
|
368
|
+
related_obj = getattr(self.object, name)
|
|
369
|
+
requested_pk = htmx_request.QUERY.get(name)
|
|
370
|
+
if related_obj and (related_obj.pk == requested_pk):
|
|
371
|
+
setattr(self.object, name, None)
|
|
372
|
+
self.object.save(update_fields=[name])
|
|
373
|
+
else:
|
|
374
|
+
raise BadRequest
|
|
375
|
+
else:
|
|
376
|
+
# Delete the object
|
|
377
|
+
self.object.delete()
|
|
378
|
+
|
|
379
|
+
if message := self.get_success_message({}):
|
|
380
|
+
messages.error(request, message)
|
|
381
|
+
|
|
382
|
+
if cast('HtmxRequest', self.request).htmx:
|
|
383
|
+
# No need to redirect, just render the normal GET response
|
|
384
|
+
response = self.render_to_response(self.get_context_data())
|
|
385
|
+
else:
|
|
386
|
+
response = HttpResponseRedirect(self.get_success_url())
|
|
387
|
+
return response
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "django-htmx-cbv"
|
|
3
|
+
version = "0.0.1.dev1"
|
|
4
|
+
description = "Django class-based views, tailored for htmx"
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Geoffrey Eisenbarth",email = "geoffrey.eisenbarth@gmail.com"}
|
|
7
|
+
]
|
|
8
|
+
license = "MIT"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.14"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"django (>=6.0.0,<7.0.0)",
|
|
13
|
+
"django-htmx (>=1.27.0,<2.0.0)",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[dependency-groups]
|
|
17
|
+
dev = [
|
|
18
|
+
"ipython (>=9.12.0,<10.0.0)",
|
|
19
|
+
"ipdb (>=0.13.13,<0.14.0)",
|
|
20
|
+
"flake8 (>=7.3.0,<8.0.0)",
|
|
21
|
+
"flake8-type-checking (>=3.2.0,<4.0.0)",
|
|
22
|
+
"mypy (>=1.20.1,<2.0.0)",
|
|
23
|
+
"django-stubs (>=6.0.2,<7.0.0)",
|
|
24
|
+
"django-stubs-ext (>=6.0.2,<7.0.0)",
|
|
25
|
+
"pytest (>=9.0.3,<10.0.0)",
|
|
26
|
+
"pytest-django (>=4.12.0,<5.0.0)",
|
|
27
|
+
"codecov (>=2.1.13,<3.0.0)",
|
|
28
|
+
"parameterized (>=0.9.0,<0.10.0)",
|
|
29
|
+
"beautifulsoup4 (>=4.14.3,<5.0.0)",
|
|
30
|
+
"pre-commit (>=4.5.1,<5.0.0)"
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
36
|
+
build-backend = "poetry.core.masonry.api"
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
DJANGO_SETTINGS_MODULE = "project.settings"
|
|
40
|
+
pythonpath = ["tests/project"]
|
|
41
|
+
|
|
42
|
+
[tool.coverage.report]
|
|
43
|
+
show_missing = true
|
|
44
|
+
|
|
45
|
+
[tool.mypy]
|
|
46
|
+
python_version = "3.14"
|
|
47
|
+
plugins = ["mypy_django_plugin.main"]
|
|
48
|
+
mypy_path = ["tests/project"]
|
|
49
|
+
ignore_missing_imports = true
|
|
50
|
+
strict = true
|
|
51
|
+
exclude = [
|
|
52
|
+
"manage.py",
|
|
53
|
+
"settings.py",
|
|
54
|
+
"future.py",
|
|
55
|
+
"tests/project/",
|
|
56
|
+
]
|
|
57
|
+
files = ["django_htmx_cbv/"]
|
|
58
|
+
|
|
59
|
+
[tool.django-stubs]
|
|
60
|
+
django_settings_module = "project.settings"
|