django-admin-remote 0.1.0__tar.gz → 0.3.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.
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/CHANGELOG.md +22 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/PKG-INFO +36 -5
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/README.md +35 -4
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/pyproject.toml +1 -1
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/__init__.py +3 -2
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/client.py +12 -8
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/exceptions.py +18 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/form.py +88 -4
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/test_client.py +15 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/test_form.py +90 -2
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/.gitignore +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/LICENSE +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/dates.py +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/parse.py +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/py.typed +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/conftest.py +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/fixtures/change_form.html +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/fixtures/changelist.html +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/test_dates.py +0 -0
- {django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/tests/test_parse.py +0 -0
|
@@ -3,6 +3,28 @@
|
|
|
3
3
|
All notable changes to this project are listed here.
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## 0.3.0 - 2026-11-27
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
|
|
10
|
+
- Error banner check. After a form post the admin may answer 200 with an error or warning banner instead of redirecting. `AdminForm.banners()` returns the message list by level, `AdminForm.success_messages` the success texts, and `AdminForm.check_banners(require_success=False, allow_warnings=False)` raises the new `AdminBannerError` (a `FormError` subclass with `.errors`, `.warnings`, `.success`).
|
|
11
|
+
- `AdminForm.submit(..., check_banners=True, require_success=False)` runs that check on the answer.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- Nothing by default: `submit()` behaves as before unless `check_banners=True` is passed.
|
|
16
|
+
|
|
17
|
+
## 0.2.0 - 2026-11-26
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- File uploads. `AdminForm.file_fields`, `has_file()` and `set_file(name, filename, content, content_type)` attach a file to a file input, and `add_row` takes `(filename, content[, content_type])` for an inline file input. A form with an attached file is submitted as `multipart/form-data`.
|
|
22
|
+
- `AdminClient.post()` and `request()` take `files=` (passed to `requests`); a redirect after the POST is followed with a plain GET.
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- A file input with nothing attached is still left out of the POST (keeps the stored file), as before.
|
|
27
|
+
|
|
6
28
|
## 0.1.0 - 2026-11-11
|
|
7
29
|
|
|
8
30
|
First release.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: django-admin-remote
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Read and edit a remote Django admin site over HTTP by parsing its stock HTML. Nothing to install on the server.
|
|
5
5
|
Project-URL: Repository, https://github.com/krushndayshmookh/django-admin-remote
|
|
6
6
|
Project-URL: Issues, https://github.com/krushndayshmookh/django-admin-remote/issues
|
|
@@ -100,19 +100,21 @@ When the session is missing or has expired the client raises `NotLoggedIn`. It n
|
|
|
100
100
|
| `AdminClient(base_url, cookies=None, storage_state=None, delay=0.4, user_agent=None, timeout=60, tz=None, login_path="/admin/login/", session=None)` | One client per site. Waits `delay` seconds between requests. |
|
|
101
101
|
| `client.login(username, password)` | Log in through the admin login form. |
|
|
102
102
|
| `client.get(path, params=None)` | GET a page, returns the HTML. |
|
|
103
|
-
| `client.post(path, data)` | POST form data, returns `(final_url, html)`. Never retried. |
|
|
103
|
+
| `client.post(path, data, files=None)` | POST form data, returns `(final_url, html)`. With `files` the body is `multipart/form-data`. Never retried. |
|
|
104
104
|
| `client.changelist(path, limit=None, params=None, **filters)` | Iterator over the ids of a change list, all pages. |
|
|
105
105
|
| `client.read(path)` | `parse_change_form` of a page: `{"fields", "inlines", "logged_out"}`. |
|
|
106
106
|
| `client.form(path)` | An `AdminForm` for an add or change page. |
|
|
107
107
|
| `client.parse_datetime(text)` | `parse_admin_datetime` with the client's `tz`. |
|
|
108
108
|
| `AdminForm.has / get / set / set_if_present` | Read and change the values that will be posted. |
|
|
109
109
|
| `AdminForm.add_row(prefix, values) / delete_row(prefix, index)` | Inline formset rows. |
|
|
110
|
+
| `AdminForm.has_file(name) / set_file(name, filename, content, content_type)` | Attach a file to a file input; the form is then posted as multipart. |
|
|
110
111
|
| `AdminForm.total(prefix) / initial(prefix) / row_text / row_link_id` | Inspect inline formsets. |
|
|
111
112
|
| `AdminForm.readonly(name) / object_id()` | Displayed read-only text, primary key from the URL. |
|
|
112
|
-
| `AdminForm.submit(button="_continue")` | POST the form, returns the resulting page as an `AdminForm`. |
|
|
113
|
+
| `AdminForm.submit(button="_continue", check_banners=False, require_success=False)` | POST the form, returns the resulting page as an `AdminForm`. |
|
|
114
|
+
| `AdminForm.banners() / success_messages / check_banners(require_success=False, allow_warnings=False)` | The admin message list by level, and a check that raises `AdminBannerError` on an error or warning banner. |
|
|
113
115
|
| `parse_change_form(html)`, `parse_changelist(html)` | The parsers, usable on HTML you fetched yourself. |
|
|
114
116
|
| `parse_admin_datetime(text, tz)` | "Nov. 11, 2026, 1:43 p.m." to `2026-11-11T13:43:00+01:00`. |
|
|
115
|
-
| `NotLoggedIn`, `FormError`, `AdminHTTPError` | Exceptions, all subclasses of `AdminError`. |
|
|
117
|
+
| `NotLoggedIn`, `FormError`, `AdminBannerError`, `AdminHTTPError` | Exceptions, all subclasses of `AdminError`. `AdminBannerError` is a `FormError`. |
|
|
116
118
|
|
|
117
119
|
Every public function and method has a docstring with the details.
|
|
118
120
|
|
|
@@ -130,6 +132,35 @@ form.submit()
|
|
|
130
132
|
|
|
131
133
|
`add_row` copies the formset's `__prefix__` template row, so hidden fields keep their defaults, and it updates `TOTAL_FORMS`. It refuses to go past `MAX_NUM_FORMS`.
|
|
132
134
|
|
|
135
|
+
### File uploads
|
|
136
|
+
|
|
137
|
+
File inputs are listed in `form.file_fields` and are not posted unless you attach a file, which keeps the stored file, like a browser. Attach one with `set_file`, or pass `(filename, content)` or `(filename, content, content_type)` for a file input in `add_row`. Text content is sent UTF-8 encoded. Any attached file makes the submit a `multipart/form-data` POST.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
form = admin.form("/admin/library/book/3/change/")
|
|
141
|
+
form.set_file("cover", "cover.png", png_bytes, "image/png")
|
|
142
|
+
form.add_row("attachment_set", {"title": "Errata", "document": ("errata.txt", "Page 4: read 12 for 21")})
|
|
143
|
+
form.submit()
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Error banners
|
|
147
|
+
|
|
148
|
+
The admin sometimes answers a POST with 200 and an error banner (a message at the error level, `p.errornote`, `ul.errorlist`) instead of redirecting. `submit()` already raises `FormError` for `errornote` and `errorlist`. For the message list too, and to insist on a success message, check the answer:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from django_admin_remote import AdminBannerError
|
|
152
|
+
|
|
153
|
+
saved = form.submit("_continue", check_banners=True, require_success=True)
|
|
154
|
+
# or on any page you hold:
|
|
155
|
+
try:
|
|
156
|
+
saved.check_banners(require_success=True)
|
|
157
|
+
except AdminBannerError as err:
|
|
158
|
+
print(err.errors, err.warnings)
|
|
159
|
+
print(saved.success_messages) # ["The thing "x" was changed successfully."]
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Warning-level messages raise too, unless `allow_warnings=True`. Without `check_banners=True`, `submit()` behaves as in 0.2.
|
|
163
|
+
|
|
133
164
|
### Dates
|
|
134
165
|
|
|
135
166
|
The admin shows datetimes in the server's time zone without naming it. Pass the zone to get an unambiguous value:
|
|
@@ -166,7 +197,7 @@ What cannot be recovered: anything the admin formats before display. Dates come
|
|
|
166
197
|
- **Be polite to production sites.** Every call is a real page render on someone's server. Keep the default delay or raise it, use `limit`, and do not run it in parallel against a site you do not operate. Only use it where you are allowed to automate.
|
|
167
198
|
- **POSTs are never retried.** If a POST fails or times out, the client raises and leaves it to you: the save may or may not have happened, and a blind repeat could create a duplicate. A GET that gets a 5xx answer is retried a few times.
|
|
168
199
|
- **A submit sends what the page showed.** Like a browser, the form posts every field back. If someone else edits the same object between your load and your submit, their change is overwritten.
|
|
169
|
-
-
|
|
200
|
+
- A file input with nothing attached is left out of the POST, which keeps the existing file. Clearing a file (the admin's "Clear" checkbox) is an ordinary checkbox field.
|
|
170
201
|
- No JavaScript. Widgets that load their choices by AJAX (`autocomplete_fields`) only list the options present in the HTML; set those fields to the primary key directly. `raw_id_fields` are plain text inputs and work.
|
|
171
202
|
- Change list parsing returns ids, the count and the pages, not the column values. Read each object for its data.
|
|
172
203
|
- The total count and the dates assume an English-language admin with default formats.
|
|
@@ -67,19 +67,21 @@ When the session is missing or has expired the client raises `NotLoggedIn`. It n
|
|
|
67
67
|
| `AdminClient(base_url, cookies=None, storage_state=None, delay=0.4, user_agent=None, timeout=60, tz=None, login_path="/admin/login/", session=None)` | One client per site. Waits `delay` seconds between requests. |
|
|
68
68
|
| `client.login(username, password)` | Log in through the admin login form. |
|
|
69
69
|
| `client.get(path, params=None)` | GET a page, returns the HTML. |
|
|
70
|
-
| `client.post(path, data)` | POST form data, returns `(final_url, html)`. Never retried. |
|
|
70
|
+
| `client.post(path, data, files=None)` | POST form data, returns `(final_url, html)`. With `files` the body is `multipart/form-data`. Never retried. |
|
|
71
71
|
| `client.changelist(path, limit=None, params=None, **filters)` | Iterator over the ids of a change list, all pages. |
|
|
72
72
|
| `client.read(path)` | `parse_change_form` of a page: `{"fields", "inlines", "logged_out"}`. |
|
|
73
73
|
| `client.form(path)` | An `AdminForm` for an add or change page. |
|
|
74
74
|
| `client.parse_datetime(text)` | `parse_admin_datetime` with the client's `tz`. |
|
|
75
75
|
| `AdminForm.has / get / set / set_if_present` | Read and change the values that will be posted. |
|
|
76
76
|
| `AdminForm.add_row(prefix, values) / delete_row(prefix, index)` | Inline formset rows. |
|
|
77
|
+
| `AdminForm.has_file(name) / set_file(name, filename, content, content_type)` | Attach a file to a file input; the form is then posted as multipart. |
|
|
77
78
|
| `AdminForm.total(prefix) / initial(prefix) / row_text / row_link_id` | Inspect inline formsets. |
|
|
78
79
|
| `AdminForm.readonly(name) / object_id()` | Displayed read-only text, primary key from the URL. |
|
|
79
|
-
| `AdminForm.submit(button="_continue")` | POST the form, returns the resulting page as an `AdminForm`. |
|
|
80
|
+
| `AdminForm.submit(button="_continue", check_banners=False, require_success=False)` | POST the form, returns the resulting page as an `AdminForm`. |
|
|
81
|
+
| `AdminForm.banners() / success_messages / check_banners(require_success=False, allow_warnings=False)` | The admin message list by level, and a check that raises `AdminBannerError` on an error or warning banner. |
|
|
80
82
|
| `parse_change_form(html)`, `parse_changelist(html)` | The parsers, usable on HTML you fetched yourself. |
|
|
81
83
|
| `parse_admin_datetime(text, tz)` | "Nov. 11, 2026, 1:43 p.m." to `2026-11-11T13:43:00+01:00`. |
|
|
82
|
-
| `NotLoggedIn`, `FormError`, `AdminHTTPError` | Exceptions, all subclasses of `AdminError`. |
|
|
84
|
+
| `NotLoggedIn`, `FormError`, `AdminBannerError`, `AdminHTTPError` | Exceptions, all subclasses of `AdminError`. `AdminBannerError` is a `FormError`. |
|
|
83
85
|
|
|
84
86
|
Every public function and method has a docstring with the details.
|
|
85
87
|
|
|
@@ -97,6 +99,35 @@ form.submit()
|
|
|
97
99
|
|
|
98
100
|
`add_row` copies the formset's `__prefix__` template row, so hidden fields keep their defaults, and it updates `TOTAL_FORMS`. It refuses to go past `MAX_NUM_FORMS`.
|
|
99
101
|
|
|
102
|
+
### File uploads
|
|
103
|
+
|
|
104
|
+
File inputs are listed in `form.file_fields` and are not posted unless you attach a file, which keeps the stored file, like a browser. Attach one with `set_file`, or pass `(filename, content)` or `(filename, content, content_type)` for a file input in `add_row`. Text content is sent UTF-8 encoded. Any attached file makes the submit a `multipart/form-data` POST.
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
form = admin.form("/admin/library/book/3/change/")
|
|
108
|
+
form.set_file("cover", "cover.png", png_bytes, "image/png")
|
|
109
|
+
form.add_row("attachment_set", {"title": "Errata", "document": ("errata.txt", "Page 4: read 12 for 21")})
|
|
110
|
+
form.submit()
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Error banners
|
|
114
|
+
|
|
115
|
+
The admin sometimes answers a POST with 200 and an error banner (a message at the error level, `p.errornote`, `ul.errorlist`) instead of redirecting. `submit()` already raises `FormError` for `errornote` and `errorlist`. For the message list too, and to insist on a success message, check the answer:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from django_admin_remote import AdminBannerError
|
|
119
|
+
|
|
120
|
+
saved = form.submit("_continue", check_banners=True, require_success=True)
|
|
121
|
+
# or on any page you hold:
|
|
122
|
+
try:
|
|
123
|
+
saved.check_banners(require_success=True)
|
|
124
|
+
except AdminBannerError as err:
|
|
125
|
+
print(err.errors, err.warnings)
|
|
126
|
+
print(saved.success_messages) # ["The thing "x" was changed successfully."]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Warning-level messages raise too, unless `allow_warnings=True`. Without `check_banners=True`, `submit()` behaves as in 0.2.
|
|
130
|
+
|
|
100
131
|
### Dates
|
|
101
132
|
|
|
102
133
|
The admin shows datetimes in the server's time zone without naming it. Pass the zone to get an unambiguous value:
|
|
@@ -133,7 +164,7 @@ What cannot be recovered: anything the admin formats before display. Dates come
|
|
|
133
164
|
- **Be polite to production sites.** Every call is a real page render on someone's server. Keep the default delay or raise it, use `limit`, and do not run it in parallel against a site you do not operate. Only use it where you are allowed to automate.
|
|
134
165
|
- **POSTs are never retried.** If a POST fails or times out, the client raises and leaves it to you: the save may or may not have happened, and a blind repeat could create a duplicate. A GET that gets a 5xx answer is retried a few times.
|
|
135
166
|
- **A submit sends what the page showed.** Like a browser, the form posts every field back. If someone else edits the same object between your load and your submit, their change is overwritten.
|
|
136
|
-
-
|
|
167
|
+
- A file input with nothing attached is left out of the POST, which keeps the existing file. Clearing a file (the admin's "Clear" checkbox) is an ordinary checkbox field.
|
|
137
168
|
- No JavaScript. Widgets that load their choices by AJAX (`autocomplete_fields`) only list the options present in the HTML; set those fields to the primary key directly. `raw_id_fields` are plain text inputs and work.
|
|
138
169
|
- Change list parsing returns ids, the count and the pages, not the column values. Read each object for its data.
|
|
139
170
|
- The total count and the dates assume an English-language admin with default formats.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "django-admin-remote"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Read and edit a remote Django admin site over HTTP by parsing its stock HTML. Nothing to install on the server."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -2,17 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
Nothing is installed on the server. See the README for a quickstart.
|
|
4
4
|
"""
|
|
5
|
-
__version__ = "0.
|
|
5
|
+
__version__ = "0.3.0"
|
|
6
6
|
|
|
7
7
|
from .client import AdminClient
|
|
8
8
|
from .dates import parse_admin_datetime
|
|
9
|
-
from .exceptions import AdminError, AdminHTTPError, FormError, NotLoggedIn
|
|
9
|
+
from .exceptions import AdminBannerError, AdminError, AdminHTTPError, FormError, NotLoggedIn
|
|
10
10
|
from .form import AdminForm
|
|
11
11
|
from .parse import field_value, parse_change_form, parse_changelist
|
|
12
12
|
|
|
13
13
|
__all__ = [
|
|
14
14
|
"AdminClient",
|
|
15
15
|
"AdminForm",
|
|
16
|
+
"AdminBannerError",
|
|
16
17
|
"AdminError",
|
|
17
18
|
"AdminHTTPError",
|
|
18
19
|
"FormError",
|
|
@@ -126,21 +126,22 @@ class AdminClient:
|
|
|
126
126
|
return path.rstrip("/") == self.login_path.rstrip("/") or "login" in path.strip("/").split("/")
|
|
127
127
|
|
|
128
128
|
# ---------- HTTP ----------
|
|
129
|
-
def _send(self, method: str, url: str, params: Any, data: Any, referer: str
|
|
129
|
+
def _send(self, method: str, url: str, params: Any, data: Any, referer: str,
|
|
130
|
+
files: Any = None) -> requests.Response:
|
|
130
131
|
if self._last is not None:
|
|
131
132
|
wait = self.delay - (time.monotonic() - self._last)
|
|
132
133
|
if wait > 0:
|
|
133
134
|
time.sleep(wait)
|
|
134
135
|
headers = {"Referer": referer} if method == "POST" else {}
|
|
135
136
|
try:
|
|
136
|
-
return self.http.request(method, url, params=params, data=data,
|
|
137
|
-
timeout=self.timeout, allow_redirects=False)
|
|
137
|
+
return self.http.request(method, url, params=params, data=data, files=files or None,
|
|
138
|
+
headers=headers, timeout=self.timeout, allow_redirects=False)
|
|
138
139
|
finally:
|
|
139
140
|
self._last = time.monotonic()
|
|
140
141
|
self.requests_made += 1
|
|
141
142
|
|
|
142
143
|
def request(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None,
|
|
143
|
-
data: Optional[FormData] = None) -> Tuple[str, str]:
|
|
144
|
+
data: Optional[FormData] = None, files: Optional[Mapping[str, Any]] = None) -> Tuple[str, str]:
|
|
144
145
|
"""Send one request and follow its redirects. Returns ``(final_url, body)``.
|
|
145
146
|
|
|
146
147
|
Raises NotLoggedIn if the site redirects to a login page or to another host,
|
|
@@ -151,7 +152,7 @@ class AdminClient:
|
|
|
151
152
|
referer = url
|
|
152
153
|
redirects = failures = 0
|
|
153
154
|
while True:
|
|
154
|
-
r = self._send(method, url, params, data, referer)
|
|
155
|
+
r = self._send(method, url, params, data, referer, files)
|
|
155
156
|
if r.status_code in _REDIRECTS:
|
|
156
157
|
target = urljoin(r.url or url, r.headers.get("Location", ""))
|
|
157
158
|
if method == "POST" and r.status_code in (307, 308):
|
|
@@ -162,7 +163,7 @@ class AdminClient:
|
|
|
162
163
|
redirects += 1
|
|
163
164
|
if redirects > self.max_redirects:
|
|
164
165
|
raise AdminHTTPError(f"too many redirects from {url}", r.status_code, url)
|
|
165
|
-
url, method, params, data = target, "GET", None, None
|
|
166
|
+
url, method, params, data, files = target, "GET", None, None, None
|
|
166
167
|
continue
|
|
167
168
|
if r.status_code >= 500 and method == "GET" and failures < self.get_retries:
|
|
168
169
|
failures += 1
|
|
@@ -177,15 +178,18 @@ class AdminClient:
|
|
|
177
178
|
"""GET a page and return its HTML."""
|
|
178
179
|
return self.request("GET", path, params=params)[1]
|
|
179
180
|
|
|
180
|
-
def post(self, path: str, data: FormData) -> Tuple[str, str]:
|
|
181
|
+
def post(self, path: str, data: FormData, files: Optional[Mapping[str, Any]] = None) -> Tuple[str, str]:
|
|
181
182
|
"""POST form data. Returns ``(final_url, body)`` of the page the site lands on.
|
|
182
183
|
|
|
183
184
|
``data`` must contain ``csrfmiddlewaretoken`` (AdminForm takes care of that). The
|
|
184
185
|
Referer header Django's CSRF check wants on HTTPS is added. A POST is sent once
|
|
185
186
|
and never retried: a repeated POST could create a second object.
|
|
187
|
+
|
|
188
|
+
``files`` maps file field names to ``(filename, content, content_type)``; with it the
|
|
189
|
+
body is sent as ``multipart/form-data`` (what a browser does when a file is chosen).
|
|
186
190
|
"""
|
|
187
191
|
self.posts_made += 1
|
|
188
|
-
return self.request("POST", path, data=data)
|
|
192
|
+
return self.request("POST", path, data=data, files=files)
|
|
189
193
|
|
|
190
194
|
# ---------- login ----------
|
|
191
195
|
def login(self, username: str, password: str) -> None:
|
{django_admin_remote-0.1.0 → django_admin_remote-0.3.0}/src/django_admin_remote/exceptions.py
RENAMED
|
@@ -14,6 +14,24 @@ class FormError(AdminError):
|
|
|
14
14
|
"""A form could not be filled in or the admin rejected it with validation errors."""
|
|
15
15
|
|
|
16
16
|
|
|
17
|
+
class AdminBannerError(FormError):
|
|
18
|
+
"""The admin answered 200 with an error or warning banner (or no success message) instead of redirecting.
|
|
19
|
+
|
|
20
|
+
A FormError subclass, so ``except FormError`` still catches it.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
errors: texts of the error banners (message list at the error level, errornote, errorlist).
|
|
24
|
+
warnings: texts of the warning banners.
|
|
25
|
+
success: texts of the success messages the page showed.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, errors=(), warnings=(), success=()) -> None:
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.errors = list(errors)
|
|
31
|
+
self.warnings = list(warnings)
|
|
32
|
+
self.success = list(success)
|
|
33
|
+
|
|
34
|
+
|
|
17
35
|
class AdminHTTPError(AdminError):
|
|
18
36
|
"""The site answered with an HTTP error status.
|
|
19
37
|
|
|
@@ -7,11 +7,11 @@ Save in the browser.
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
9
|
import re
|
|
10
|
-
from typing import Any, Dict, List, Optional, Tuple
|
|
10
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
11
11
|
|
|
12
12
|
from bs4 import Tag
|
|
13
13
|
|
|
14
|
-
from .exceptions import FormError, NotLoggedIn
|
|
14
|
+
from .exceptions import AdminBannerError, FormError, NotLoggedIn
|
|
15
15
|
from .parse import is_login_page, soup
|
|
16
16
|
|
|
17
17
|
SKIP_TYPES = {"submit", "button", "file", "image", "reset"}
|
|
@@ -55,6 +55,13 @@ def _default_values(el: Tag) -> Optional[List[str]]:
|
|
|
55
55
|
return [el.get("value", "")]
|
|
56
56
|
|
|
57
57
|
|
|
58
|
+
def _is_file(el: Tag) -> bool:
|
|
59
|
+
return el.name == "input" and (el.get("type") or "").lower() == "file" and not el.has_attr("disabled")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
FileValue = Union[Tuple[str, Union[str, bytes]], Tuple[str, Union[str, bytes], str]]
|
|
63
|
+
|
|
64
|
+
|
|
58
65
|
class AdminForm:
|
|
59
66
|
"""One admin add or change form.
|
|
60
67
|
|
|
@@ -73,6 +80,8 @@ class AdminForm:
|
|
|
73
80
|
buttons: names of the submit buttons on the form.
|
|
74
81
|
messages: texts of the admin's message list (for example "... was changed successfully.").
|
|
75
82
|
errors: validation errors shown on the page.
|
|
83
|
+
file_fields: names of the file inputs the form would post (see :meth:`set_file`).
|
|
84
|
+
files: ``{name: (filename, content, content_type)}`` attached so far.
|
|
76
85
|
"""
|
|
77
86
|
|
|
78
87
|
def __init__(self, client: Any, path: str, text: Optional[str] = None) -> None:
|
|
@@ -109,6 +118,8 @@ class AdminForm:
|
|
|
109
118
|
self.templates: Dict[str, Dict[str, Tag]] = {}
|
|
110
119
|
self.buttons: List[str] = []
|
|
111
120
|
self._button_values: Dict[str, str] = {}
|
|
121
|
+
self.file_fields: set = set()
|
|
122
|
+
self.files: Dict[str, Tuple[str, bytes, str]] = {}
|
|
112
123
|
self.messages = [li.get_text(" ", strip=True) for li in doc.select("ul.messagelist li")]
|
|
113
124
|
self.errors = [e.get_text(" ", strip=True) for e in doc.select("p.errornote, ul.errorlist li")]
|
|
114
125
|
if form is None:
|
|
@@ -129,6 +140,9 @@ class AdminForm:
|
|
|
129
140
|
if m:
|
|
130
141
|
self.templates.setdefault(m.group(1), {})[m.group(2)] = el
|
|
131
142
|
continue
|
|
143
|
+
if _is_file(el):
|
|
144
|
+
self.file_fields.add(name)
|
|
145
|
+
continue
|
|
132
146
|
vals = _default_values(el)
|
|
133
147
|
if vals is None:
|
|
134
148
|
continue
|
|
@@ -240,6 +254,22 @@ class AdminForm:
|
|
|
240
254
|
else:
|
|
241
255
|
self.fields[name] = [self._resolve(name, value)]
|
|
242
256
|
|
|
257
|
+
def has_file(self, name: str) -> bool:
|
|
258
|
+
"""True if the form has a file input with this name that a browser would post."""
|
|
259
|
+
return name in self.file_fields
|
|
260
|
+
|
|
261
|
+
def set_file(self, name: str, filename: str, content: Union[str, bytes],
|
|
262
|
+
content_type: str = "application/octet-stream") -> None:
|
|
263
|
+
"""Attach a file to a file input, as choosing a file in the browser would.
|
|
264
|
+
|
|
265
|
+
``content`` is bytes, or text that is sent UTF-8 encoded. The form is then posted as
|
|
266
|
+
``multipart/form-data``. Raises FormError if the page has no such file input.
|
|
267
|
+
"""
|
|
268
|
+
if name not in self.file_fields:
|
|
269
|
+
raise FormError(f"file field {name!r} is not on {self.path}")
|
|
270
|
+
data = content.encode("utf-8") if isinstance(content, str) else bytes(content)
|
|
271
|
+
self.files[name] = (filename, data, content_type)
|
|
272
|
+
|
|
243
273
|
def set_if_present(self, name: str, value: Any) -> bool:
|
|
244
274
|
"""Set the field if it is editable here and value is not None. Returns whether it was set."""
|
|
245
275
|
if name in self.fields and value is not None:
|
|
@@ -253,6 +283,8 @@ class AdminForm:
|
|
|
253
283
|
The row is built from the formset's ``__prefix__`` empty-form template, so hidden
|
|
254
284
|
fields such as the parent key keep their defaults, and TOTAL_FORMS is increased.
|
|
255
285
|
``values`` maps the short field names of the inline to values (see :meth:`set`).
|
|
286
|
+
A file input of the inline takes ``(filename, content)`` or
|
|
287
|
+
``(filename, content, content_type)`` (see :meth:`set_file`).
|
|
256
288
|
"""
|
|
257
289
|
tmpl = self.templates.get(prefix)
|
|
258
290
|
if tmpl is None or not self.has_inline(prefix):
|
|
@@ -266,6 +298,11 @@ class AdminForm:
|
|
|
266
298
|
raise FormError(f"inline {prefix!r} has no field(s) {sorted(unknown)}. Has: {sorted(tmpl)}")
|
|
267
299
|
for field, el in tmpl.items():
|
|
268
300
|
name = f"{prefix}-{index}-{field}"
|
|
301
|
+
if _is_file(el):
|
|
302
|
+
self.file_fields.add(name)
|
|
303
|
+
if field in values and values[field] is not None:
|
|
304
|
+
self.set_file(name, *values[field])
|
|
305
|
+
continue
|
|
269
306
|
vals = _default_values(el)
|
|
270
307
|
if vals is None:
|
|
271
308
|
continue
|
|
@@ -281,7 +318,8 @@ class AdminForm:
|
|
|
281
318
|
"""Tick the DELETE box of a saved inline row. It is deleted when the form is submitted."""
|
|
282
319
|
self.set(f"{prefix}-{index}-DELETE", True)
|
|
283
320
|
|
|
284
|
-
def submit(self, button: str = "_continue"
|
|
321
|
+
def submit(self, button: str = "_continue", check_banners: bool = False,
|
|
322
|
+
require_success: bool = False) -> "AdminForm":
|
|
285
323
|
"""POST the form by "pressing" the named submit button.
|
|
286
324
|
|
|
287
325
|
The default ``_continue`` is "Save and continue editing", which lands back on the
|
|
@@ -291,6 +329,10 @@ class AdminForm:
|
|
|
291
329
|
Returns the page the admin answered with as a new AdminForm. Raises FormError if
|
|
292
330
|
the button does not exist or the admin reports validation errors. The POST is sent
|
|
293
331
|
once and never retried.
|
|
332
|
+
|
|
333
|
+
With ``check_banners=True`` the answer is also run through :meth:`check_banners`
|
|
334
|
+
(``require_success`` is passed on), so an error or warning banner that came with a
|
|
335
|
+
200 page raises :class:`AdminBannerError`. Off by default.
|
|
294
336
|
"""
|
|
295
337
|
if self.form is None:
|
|
296
338
|
raise FormError(f"no form found on {self.path}")
|
|
@@ -298,12 +340,54 @@ class AdminForm:
|
|
|
298
340
|
raise FormError(f"button {button!r} not on {self.path}. Has: {self.buttons}")
|
|
299
341
|
data = [(n, v) for n, vals in self.fields.items() for v in vals]
|
|
300
342
|
data.append((button, self._button_values.get(button, "1")))
|
|
301
|
-
|
|
343
|
+
if self.files:
|
|
344
|
+
url, text = self.client.post(self.path, data, files=dict(self.files))
|
|
345
|
+
else:
|
|
346
|
+
url, text = self.client.post(self.path, data)
|
|
302
347
|
result = AdminForm(self.client, url, text)
|
|
303
348
|
if result.errors:
|
|
304
349
|
raise FormError(f"{self.path} rejected: {result.errors[:6]}")
|
|
350
|
+
if check_banners:
|
|
351
|
+
result.check_banners(require_success=require_success)
|
|
305
352
|
return result
|
|
306
353
|
|
|
354
|
+
def banners(self) -> Dict[str, List[str]]:
|
|
355
|
+
"""The admin's message list by level: ``{"success": [...], "warning": [...], "error": [...], "info": [...]}``.
|
|
356
|
+
|
|
357
|
+
The level is the CSS class of the message (``success``, ``warning``, ``error``);
|
|
358
|
+
a message with none of them counts as ``info``.
|
|
359
|
+
"""
|
|
360
|
+
out: Dict[str, List[str]] = {"success": [], "warning": [], "error": [], "info": []}
|
|
361
|
+
for li in self.doc.select("ul.messagelist li"):
|
|
362
|
+
level = next((c for c in li.get("class") or [] if c in out), "info")
|
|
363
|
+
out[level].append(li.get_text(" ", strip=True))
|
|
364
|
+
return out
|
|
365
|
+
|
|
366
|
+
@property
|
|
367
|
+
def success_messages(self) -> List[str]:
|
|
368
|
+
"""Texts of the success messages on the page (for example "... was changed successfully.")."""
|
|
369
|
+
return self.banners()["success"]
|
|
370
|
+
|
|
371
|
+
def check_banners(self, require_success: bool = False, allow_warnings: bool = False) -> Dict[str, List[str]]:
|
|
372
|
+
"""Raise :class:`AdminBannerError` if the page carries an error banner.
|
|
373
|
+
|
|
374
|
+
Error banners are error-level messages, ``p.errornote`` and ``ul.errorlist`` items.
|
|
375
|
+
Warning-level messages count too unless ``allow_warnings`` is true. With
|
|
376
|
+
``require_success=True`` a page without any success message raises as well (a save
|
|
377
|
+
that the admin did not confirm). Returns :meth:`banners` when the page is fine.
|
|
378
|
+
"""
|
|
379
|
+
seen = self.banners()
|
|
380
|
+
errors = seen["error"] + [e for e in self.errors if e not in seen["error"]]
|
|
381
|
+
warnings = [] if allow_warnings else seen["warning"]
|
|
382
|
+
bad = errors + warnings
|
|
383
|
+
if bad:
|
|
384
|
+
raise AdminBannerError(f"{self.path}: the admin reported: {'; '.join(bad)}",
|
|
385
|
+
errors, warnings, seen["success"])
|
|
386
|
+
if require_success and not seen["success"]:
|
|
387
|
+
raise AdminBannerError(f"{self.path}: the admin did not confirm the change (no success message)",
|
|
388
|
+
errors, warnings, seen["success"])
|
|
389
|
+
return seen
|
|
390
|
+
|
|
307
391
|
def object_id(self) -> Optional[int]:
|
|
308
392
|
"""Numeric primary key from the page path, None on an add page."""
|
|
309
393
|
m = re.search(r"/(\d+)/change/", self.path)
|
|
@@ -264,3 +264,18 @@ def test_parse_datetime_uses_the_client_zone(make_client):
|
|
|
264
264
|
client, _ = make_client(lambda call: (200, {}, INDEX_PAGE))
|
|
265
265
|
with pytest.raises(ValueError):
|
|
266
266
|
client.parse_datetime("Oct. 30, 2026, noon")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def test_post_with_files_is_multipart(make_client):
|
|
270
|
+
client, transport = make_client(lambda call: (200, {}, "ok"))
|
|
271
|
+
client.post("/admin/app/thing/5/change/", [("title", "New")], files={"upload": ("a.txt", b"hello", "text/plain")})
|
|
272
|
+
(post,) = transport.calls
|
|
273
|
+
assert post["headers"]["Content-Type"].startswith("multipart/form-data")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def test_post_without_files_stays_urlencoded(make_client):
|
|
277
|
+
client, transport = make_client(lambda call: (200, {}, "ok"))
|
|
278
|
+
client.post("/admin/app/thing/5/change/", [("title", "New")])
|
|
279
|
+
(post,) = transport.calls
|
|
280
|
+
assert post["headers"]["Content-Type"] == "application/x-www-form-urlencoded"
|
|
281
|
+
assert post["form"] == [("title", "New")]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import pytest
|
|
2
2
|
|
|
3
|
-
from django_admin_remote import AdminForm, FormError, NotLoggedIn
|
|
3
|
+
from django_admin_remote import AdminBannerError, AdminForm, FormError, NotLoggedIn
|
|
4
4
|
|
|
5
5
|
PAGE = """
|
|
6
6
|
<html><body><div id="content">
|
|
@@ -50,8 +50,9 @@ class FakeClient:
|
|
|
50
50
|
def request(self, method, path):
|
|
51
51
|
return self.lands_on or path, PAGE
|
|
52
52
|
|
|
53
|
-
def post(self, path, data):
|
|
53
|
+
def post(self, path, data, **kwargs):
|
|
54
54
|
self.posted = (path, data)
|
|
55
|
+
self.files = kwargs.get("files")
|
|
55
56
|
return self.lands_on or path, self.answer
|
|
56
57
|
|
|
57
58
|
|
|
@@ -158,3 +159,90 @@ def test_base_url_is_only_stripped_as_a_whole_prefix():
|
|
|
158
159
|
assert AdminForm(c, other, PAGE).path == other
|
|
159
160
|
assert AdminForm(c, "https://admin.example.com", PAGE).path == "/"
|
|
160
161
|
assert AdminForm(FakeClient(), "https://x.test/admin/a/b/1/change/", PAGE).path == "https://x.test/admin/a/b/1/change/"
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
INLINE_FILE_PAGE = """
|
|
165
|
+
<html><body><div id="content"><form method="post"><input type="hidden" name="csrfmiddlewaretoken" value="tok">
|
|
166
|
+
<input type="hidden" name="cases-TOTAL_FORMS" value="0"><input type="hidden" name="cases-INITIAL_FORMS" value="0">
|
|
167
|
+
<input type="hidden" name="cases-MIN_NUM_FORMS" value="0"><input type="hidden" name="cases-MAX_NUM_FORMS" value="10">
|
|
168
|
+
<table><tr class="empty-form"><td><textarea name="cases-__prefix__-output"></textarea>
|
|
169
|
+
<input type="file" name="cases-__prefix__-output_file"><input type="file" name="cases-__prefix__-locked_file" disabled></td></tr></table>
|
|
170
|
+
<input type="submit" name="_continue" value="Save and continue editing"></form></div></body></html>
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def test_file_input_is_known_but_not_posted_as_a_field():
|
|
175
|
+
f = form()
|
|
176
|
+
assert f.has_file("upload") and not f.has("upload")
|
|
177
|
+
c = FakeClient()
|
|
178
|
+
AdminForm(c, "/admin/app/thing/5/change/", PAGE).submit()
|
|
179
|
+
assert c.files is None and "upload" not in dict(c.posted[1])
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def test_set_file_sends_multipart_files():
|
|
183
|
+
c = FakeClient()
|
|
184
|
+
f = AdminForm(c, "/admin/app/thing/5/change/", PAGE)
|
|
185
|
+
f.set_file("upload", "big.txt", "x" * 3000, "text/plain")
|
|
186
|
+
f.submit()
|
|
187
|
+
assert c.files == {"upload": ("big.txt", b"x" * 3000, "text/plain")}
|
|
188
|
+
assert ("title", "Old") in c.posted[1]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def test_set_file_on_unknown_field_raises():
|
|
192
|
+
with pytest.raises(FormError):
|
|
193
|
+
form().set_file("nope", "a.txt", b"1")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def test_add_row_takes_a_file_for_an_inline_file_input():
|
|
197
|
+
c = FakeClient()
|
|
198
|
+
f = AdminForm(c, "/admin/app/question/9/change/", INLINE_FILE_PAGE)
|
|
199
|
+
i = f.add_row("cases", {"output": "", "output_file": ("out.txt", "long output")})
|
|
200
|
+
assert f.has_file(f"cases-{i}-output_file") and not f.has_file(f"cases-{i}-locked_file")
|
|
201
|
+
f.submit()
|
|
202
|
+
assert c.files == {"cases-0-output_file": ("out.txt", b"long output", "application/octet-stream")}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _with_messages(*items):
|
|
206
|
+
lis = "".join(f'<li class="{c}">{t}</li>' for c, t in items)
|
|
207
|
+
return PAGE.replace('<div id="content">', f'<div id="content"><ul class="messagelist">{lis}</ul>', 1)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def test_banners_by_level_and_success_messages():
|
|
211
|
+
page = _with_messages(("success", "Saved."), ("warning", "Careful"), ("error", "Nope"), ("", "FYI"))
|
|
212
|
+
f = AdminForm(FakeClient(), "/admin/app/thing/5/change/", page)
|
|
213
|
+
assert f.banners() == {"success": ["Saved."], "warning": ["Careful"], "error": ["Nope"], "info": ["FYI"]}
|
|
214
|
+
assert f.success_messages == ["Saved."]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_check_banners_raises_with_messages():
|
|
218
|
+
page = _with_messages(("error", "Could not run it"), ("warning", "Slow"))
|
|
219
|
+
f = AdminForm(FakeClient(), "/admin/app/thing/5/change/", page)
|
|
220
|
+
with pytest.raises(AdminBannerError) as exc:
|
|
221
|
+
f.check_banners()
|
|
222
|
+
assert exc.value.errors == ["Could not run it"] and exc.value.warnings == ["Slow"]
|
|
223
|
+
assert "Could not run it" in str(exc.value) and isinstance(exc.value, FormError)
|
|
224
|
+
with pytest.raises(AdminBannerError):
|
|
225
|
+
f.check_banners(allow_warnings=True) # the error still counts
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def test_check_banners_warning_and_success_rules():
|
|
229
|
+
f = AdminForm(FakeClient(), "/p/", _with_messages(("warning", "Slow"), ("success", "ok")))
|
|
230
|
+
with pytest.raises(AdminBannerError):
|
|
231
|
+
f.check_banners()
|
|
232
|
+
assert f.check_banners(allow_warnings=True)["success"] == ["ok"]
|
|
233
|
+
bare = AdminForm(FakeClient(), "/p/", PAGE)
|
|
234
|
+
assert bare.check_banners() is not None # no banners and success not required: fine
|
|
235
|
+
with pytest.raises(AdminBannerError, match="no success message"):
|
|
236
|
+
bare.check_banners(require_success=True)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def test_submit_checks_banners_only_when_asked():
|
|
240
|
+
page = _with_messages(("error", "Refused"))
|
|
241
|
+
f = form(FakeClient(answer=page))
|
|
242
|
+
assert f.submit("_save").banners()["error"] == ["Refused"] # default: as in 0.2
|
|
243
|
+
with pytest.raises(AdminBannerError, match="Refused"):
|
|
244
|
+
form(FakeClient(answer=page)).submit("_save", check_banners=True)
|
|
245
|
+
ok = _with_messages(("success", "Saved."))
|
|
246
|
+
assert form(FakeClient(answer=ok)).submit("_save", check_banners=True, require_success=True).success_messages == ["Saved."]
|
|
247
|
+
with pytest.raises(AdminBannerError, match="no success message"):
|
|
248
|
+
form(FakeClient()).submit("_save", check_banners=True, require_success=True)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|