django-admin-remote 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,25 @@
1
+ """Drive a remote Django admin site over HTTP by parsing its stock HTML.
2
+
3
+ Nothing is installed on the server. See the README for a quickstart.
4
+ """
5
+ __version__ = "0.1.0"
6
+
7
+ from .client import AdminClient
8
+ from .dates import parse_admin_datetime
9
+ from .exceptions import AdminError, AdminHTTPError, FormError, NotLoggedIn
10
+ from .form import AdminForm
11
+ from .parse import field_value, parse_change_form, parse_changelist
12
+
13
+ __all__ = [
14
+ "AdminClient",
15
+ "AdminForm",
16
+ "AdminError",
17
+ "AdminHTTPError",
18
+ "FormError",
19
+ "NotLoggedIn",
20
+ "field_value",
21
+ "parse_admin_datetime",
22
+ "parse_change_form",
23
+ "parse_changelist",
24
+ "__version__",
25
+ ]
@@ -0,0 +1,278 @@
1
+ """HTTP client for a remote Django admin site."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import time
7
+ from datetime import tzinfo
8
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
9
+ from urllib.parse import urljoin, urlparse
10
+
11
+ import requests
12
+
13
+ from . import __version__
14
+ from .dates import parse_admin_datetime
15
+ from .exceptions import AdminHTTPError, NotLoggedIn
16
+ from .form import AdminForm
17
+ from .parse import parse_change_form, parse_changelist, soup
18
+
19
+ _REDIRECTS = (301, 302, 303, 307, 308)
20
+ FormData = Union[Mapping[str, Any], Sequence[Tuple[str, Any]]]
21
+
22
+
23
+ class AdminClient:
24
+ """A polite client for one Django admin site.
25
+
26
+ It waits ``delay`` seconds between requests, follows redirects itself so a bounce to
27
+ the login page is noticed, retries a GET on a 5xx answer but never a POST, and refuses
28
+ to talk to any host other than ``base_url``.
29
+
30
+ Authentication is either existing session cookies (``cookies`` or ``storage_state``,
31
+ the way to go for sites behind SSO) or :meth:`login` with a username and password.
32
+
33
+ Args:
34
+ base_url: scheme and host of the site, for example ``https://admin.example.com``.
35
+ Paths given to the methods are appended to it.
36
+ cookies: session cookies as a ``{name: value}`` dict or a cookie jar.
37
+ storage_state: a Playwright ``storage_state`` (path to the JSON file, or the dict).
38
+ Only cookies whose domain matches ``base_url`` are used. Playwright itself is
39
+ not needed.
40
+ delay: minimum seconds between two requests.
41
+ user_agent: User-Agent header. Defaults to ``django-admin-remote/<version>``.
42
+ timeout: seconds to wait for each response.
43
+ tz: time zone the admin displays datetimes in (IANA name or tzinfo). Only used by
44
+ :meth:`parse_datetime`.
45
+ login_path: path of the admin login view.
46
+ session: a ``requests.Session`` to use instead of a new one (for proxies, custom
47
+ TLS settings or tests).
48
+
49
+ Attributes:
50
+ requests_made: number of HTTP requests sent so far.
51
+ posts_made: number of POSTs sent so far.
52
+ max_redirects: redirects followed per call before giving up (default 6).
53
+ get_retries: extra attempts for a GET answered with a 5xx status (default 3).
54
+ retry_backoff: seconds slept before retry n is ``retry_backoff * n`` (default 2).
55
+ """
56
+
57
+ max_redirects = 6
58
+ get_retries = 3
59
+ retry_backoff = 2.0
60
+
61
+ def __init__(
62
+ self,
63
+ base_url: str,
64
+ cookies: Any = None,
65
+ storage_state: Union[str, "os.PathLike[str]", Mapping[str, Any], None] = None,
66
+ delay: float = 0.4,
67
+ user_agent: Optional[str] = None,
68
+ timeout: float = 60.0,
69
+ tz: Union[str, tzinfo, None] = None,
70
+ login_path: str = "/admin/login/",
71
+ session: Optional[requests.Session] = None,
72
+ ) -> None:
73
+ parsed = urlparse(base_url)
74
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
75
+ raise ValueError(f"base_url must look like https://host, got {base_url!r}")
76
+ self.base_url = base_url.rstrip("/")
77
+ self.delay = delay
78
+ self.timeout = timeout
79
+ self.tz = tz
80
+ self.login_path = login_path
81
+ self.http = session if session is not None else requests.Session()
82
+ self.http.headers["User-Agent"] = user_agent or f"django-admin-remote/{__version__}"
83
+ self._origin = (parsed.scheme, parsed.netloc.lower())
84
+ self._host = (parsed.hostname or "").lower()
85
+ self._last: Optional[float] = None
86
+ self.requests_made = 0
87
+ self.posts_made = 0
88
+ if storage_state is not None:
89
+ self._load_storage_state(storage_state)
90
+ if cookies is not None:
91
+ if isinstance(cookies, Mapping):
92
+ for name, value in cookies.items():
93
+ self.http.cookies.set(name, value)
94
+ else:
95
+ self.http.cookies.update(cookies)
96
+
97
+ # ---------- cookies ----------
98
+ def _load_storage_state(self, state: Any) -> None:
99
+ if not isinstance(state, Mapping):
100
+ with open(state, encoding="utf-8") as fh:
101
+ state = json.load(fh)
102
+ for c in state.get("cookies", []):
103
+ domain = (c.get("domain") or "").lower()
104
+ bare = domain.lstrip(".")
105
+ if not bare or not (self._host == bare or self._host.endswith("." + bare)):
106
+ continue
107
+ kwargs: Dict[str, Any] = {"path": c.get("path") or "/"}
108
+ if "." in self._host: # single-label hosts (localhost) only match domainless cookies
109
+ kwargs["domain"] = domain
110
+ self.http.cookies.set(c["name"], c["value"], **kwargs)
111
+
112
+ # ---------- URLs ----------
113
+ def _same_origin(self, url: str) -> bool:
114
+ p = urlparse(url)
115
+ return (p.scheme, p.netloc.lower()) == self._origin
116
+
117
+ def _url(self, path: str) -> str:
118
+ if path.startswith(("http://", "https://")):
119
+ if not self._same_origin(path):
120
+ raise ValueError(f"{path} is outside {self.base_url}")
121
+ return path
122
+ return self.base_url + (path if path.startswith("/") else "/" + path)
123
+
124
+ def _is_login(self, url: str) -> bool:
125
+ path = urlparse(url).path
126
+ return path.rstrip("/") == self.login_path.rstrip("/") or "login" in path.strip("/").split("/")
127
+
128
+ # ---------- HTTP ----------
129
+ def _send(self, method: str, url: str, params: Any, data: Any, referer: str) -> requests.Response:
130
+ if self._last is not None:
131
+ wait = self.delay - (time.monotonic() - self._last)
132
+ if wait > 0:
133
+ time.sleep(wait)
134
+ headers = {"Referer": referer} if method == "POST" else {}
135
+ try:
136
+ return self.http.request(method, url, params=params, data=data, headers=headers,
137
+ timeout=self.timeout, allow_redirects=False)
138
+ finally:
139
+ self._last = time.monotonic()
140
+ self.requests_made += 1
141
+
142
+ def request(self, method: str, path: str, params: Optional[Mapping[str, Any]] = None,
143
+ data: Optional[FormData] = None) -> Tuple[str, str]:
144
+ """Send one request and follow its redirects. Returns ``(final_url, body)``.
145
+
146
+ Raises NotLoggedIn if the site redirects to a login page or to another host,
147
+ AdminHTTPError on a 4xx or 5xx answer.
148
+ """
149
+ method = method.upper()
150
+ url = self._url(path)
151
+ referer = url
152
+ redirects = failures = 0
153
+ while True:
154
+ r = self._send(method, url, params, data, referer)
155
+ if r.status_code in _REDIRECTS:
156
+ target = urljoin(r.url or url, r.headers.get("Location", ""))
157
+ if method == "POST" and r.status_code in (307, 308):
158
+ raise AdminHTTPError(f"POST {url} was redirected with {r.status_code} to {target}; "
159
+ "not re-sending the POST", r.status_code, url)
160
+ if not self._same_origin(target) or self._is_login(target):
161
+ raise NotLoggedIn(f"{method} {url} was redirected to {target}: no session or it expired")
162
+ redirects += 1
163
+ if redirects > self.max_redirects:
164
+ raise AdminHTTPError(f"too many redirects from {url}", r.status_code, url)
165
+ url, method, params, data = target, "GET", None, None
166
+ continue
167
+ if r.status_code >= 500 and method == "GET" and failures < self.get_retries:
168
+ failures += 1
169
+ time.sleep(self.retry_backoff * failures)
170
+ continue
171
+ if r.status_code >= 400:
172
+ raise AdminHTTPError(f"{method} {url} -> HTTP {r.status_code}: {r.text[:300]!r}",
173
+ r.status_code, url)
174
+ return r.url or url, r.text
175
+
176
+ def get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> str:
177
+ """GET a page and return its HTML."""
178
+ return self.request("GET", path, params=params)[1]
179
+
180
+ def post(self, path: str, data: FormData) -> Tuple[str, str]:
181
+ """POST form data. Returns ``(final_url, body)`` of the page the site lands on.
182
+
183
+ ``data`` must contain ``csrfmiddlewaretoken`` (AdminForm takes care of that). The
184
+ Referer header Django's CSRF check wants on HTTPS is added. A POST is sent once
185
+ and never retried: a repeated POST could create a second object.
186
+ """
187
+ self.posts_made += 1
188
+ return self.request("POST", path, data=data)
189
+
190
+ # ---------- login ----------
191
+ def login(self, username: str, password: str) -> None:
192
+ """Log in through the standard admin login form (``login_path``).
193
+
194
+ Fetches the form, then posts the credentials together with its CSRF token. The
195
+ session cookie the site sets is kept on this client. The password is not stored.
196
+ Returns quietly if the session is already logged in. Raises NotLoggedIn if the
197
+ site rejects the credentials or shows no login form.
198
+ """
199
+ url, text = self.request("GET", self.login_path)
200
+ doc = soup(text)
201
+ form = doc.select_one("#login-form")
202
+ if form is None:
203
+ pw = doc.find("input", attrs={"type": "password"})
204
+ form = pw.find_parent("form") if pw is not None else None
205
+ if form is None:
206
+ if not self._is_login(url):
207
+ return # redirected into the admin: already logged in
208
+ raise NotLoggedIn(f"no login form found at {url}")
209
+ data: List[Tuple[str, str]] = [
210
+ (i["name"], i.get("value", "")) for i in form.find_all("input", attrs={"type": "hidden"})
211
+ if i.get("name")]
212
+ user_field = "username"
213
+ if form.find("input", attrs={"name": "username"}) is None:
214
+ other = [i for i in form.find_all("input")
215
+ if i.get("name") and (i.get("type") or "text").lower() in ("text", "email")]
216
+ if other:
217
+ user_field = other[0]["name"]
218
+ data += [(user_field, username), ("password", password)]
219
+ action = urljoin(url, form.get("action") or "")
220
+ _, text = self.post(action, data)
221
+ doc = soup(text)
222
+ if doc.select_one("#login-form") is not None:
223
+ note = doc.select_one(".errornote, .errorlist")
224
+ reason = note.get_text(" ", strip=True) if note is not None else "the login form came back"
225
+ raise NotLoggedIn(f"login rejected: {reason}")
226
+
227
+ # ---------- admin pages ----------
228
+ def form(self, path: str) -> AdminForm:
229
+ """Load an add or change page as an editable :class:`AdminForm`."""
230
+ return AdminForm(self, path)
231
+
232
+ def read(self, path: str) -> Dict[str, Any]:
233
+ """Fetch a change page and parse it with :func:`parse_change_form` (read-only use)."""
234
+ parsed = parse_change_form(self.get(path))
235
+ if parsed["logged_out"]:
236
+ raise NotLoggedIn(f"{path} returned the login form: no session or it expired")
237
+ return parsed
238
+
239
+ def changelist(self, path: str, limit: Optional[int] = None,
240
+ params: Optional[Mapping[str, Any]] = None, **filters: Any) -> Iterator[Union[int, str]]:
241
+ """Iterate over the primary keys of a change list, across all its pages.
242
+
243
+ Pages are fetched lazily, one request per page, in the list's own order.
244
+
245
+ Args:
246
+ path: the change list, for example ``/admin/app/model/``.
247
+ limit: stop after this many ids.
248
+ params: query parameters as a dict, for names that are not valid keywords.
249
+ **filters: query parameters, the same ones the admin puts in the URL when a
250
+ filter or search is used (``status__exact=1``, ``q="text"``, ``o="-1"``).
251
+ """
252
+ query = dict(params or {})
253
+ query.update(filters)
254
+ query.pop("p", None)
255
+ seen = set()
256
+ page, last, offset = 1, 1, 0
257
+ while page <= last:
258
+ parsed = parse_changelist(self.get(path, dict(query, p=page + offset) if page > 1 else query))
259
+ if parsed["logged_out"]:
260
+ raise NotLoggedIn(f"{path} returned the login form: no session or it expired")
261
+ if page == 1:
262
+ last, offset = parsed["last_page"], parsed["p_offset"]
263
+ if not parsed["ids"]:
264
+ return
265
+ for pk in parsed["ids"]:
266
+ if pk in seen:
267
+ continue # a row shifted pages while we were reading
268
+ seen.add(pk)
269
+ yield pk
270
+ if limit is not None and len(seen) >= limit:
271
+ return
272
+ page += 1
273
+
274
+ def parse_datetime(self, text: Optional[str]) -> Optional[str]:
275
+ """:func:`parse_admin_datetime` using the ``tz`` this client was created with."""
276
+ if self.tz is None:
277
+ raise ValueError("create the AdminClient with tz=... to parse admin datetimes")
278
+ return parse_admin_datetime(text, self.tz)
@@ -0,0 +1,57 @@
1
+ """Turn the dates the Django admin displays into ISO 8601 strings."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from datetime import datetime, tzinfo
6
+ from typing import Optional, Union
7
+ from zoneinfo import ZoneInfo
8
+
9
+ _MONTHS = {m: i for i, m in enumerate(
10
+ ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], start=1)}
11
+
12
+
13
+ def _zone(tz: Union[str, tzinfo]) -> tzinfo:
14
+ return ZoneInfo(tz) if isinstance(tz, str) else tz
15
+
16
+
17
+ def parse_admin_datetime(text: Optional[str], tz: Union[str, tzinfo]) -> Optional[str]:
18
+ """Convert a date or datetime shown by the Django admin to ISO 8601 with a UTC offset.
19
+
20
+ The admin shows datetimes in the server's current time zone without saying which one,
21
+ so the caller has to supply it.
22
+
23
+ Args:
24
+ text: what the admin displayed. Understands Django's default English formats
25
+ ("Nov. 11, 2026, 1:43 p.m.", "Sept. 29, 2026, 3:03 a.m.", "March 1, 2026, 9 p.m.",
26
+ "Oct. 30, 2026, noon", "May 30, 2023, midnight", "May 30, 2023") and the values of
27
+ editable date and time widgets ("2026-11-11", "2026-11-11 13:43:00").
28
+ tz: the time zone the admin displays in, as an IANA name ("Europe/Paris") or a tzinfo.
29
+
30
+ Returns:
31
+ An ISO 8601 string such as "2026-11-11T13:43:00+01:00". None for empty input.
32
+ Text that does not look like a date is returned unchanged, so nothing is lost silently.
33
+ """
34
+ if not text:
35
+ return None
36
+ zone = _zone(tz)
37
+ iso = re.fullmatch(r"\s*(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?\s*", text)
38
+ if iso:
39
+ y, mo, d, h, mi, sec = (int(x or 0) for x in iso.groups())
40
+ return datetime(y, mo, d, h, mi, sec, tzinfo=zone).isoformat()
41
+ m = re.fullmatch(r"\s*([A-Za-z]+)\.?\s+(\d{1,2}),\s*(\d{4})(?:,\s*(.+?))?\s*", text)
42
+ if not m or m.group(1)[:3].lower() not in _MONTHS:
43
+ return text
44
+ month, day, year = _MONTHS[m.group(1)[:3].lower()], int(m.group(2)), int(m.group(3))
45
+ clock = (m.group(4) or "midnight").lower()
46
+ if clock == "noon":
47
+ hour, minute = 12, 0
48
+ elif clock == "midnight":
49
+ hour, minute = 0, 0
50
+ else:
51
+ t = re.fullmatch(r"(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?", clock)
52
+ if not t:
53
+ return text
54
+ hour, minute = int(t.group(1)) % 12, int(t.group(2) or 0)
55
+ if t.group(3) == "p":
56
+ hour += 12
57
+ return datetime(year, month, day, hour, minute, tzinfo=zone).isoformat()
@@ -0,0 +1,28 @@
1
+ """Exceptions raised by django-admin-remote."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class AdminError(RuntimeError):
6
+ """Base class for every error this package raises on purpose."""
7
+
8
+
9
+ class NotLoggedIn(AdminError):
10
+ """The site asked for a login: no session, an expired session, or rejected credentials."""
11
+
12
+
13
+ class FormError(AdminError):
14
+ """A form could not be filled in or the admin rejected it with validation errors."""
15
+
16
+
17
+ class AdminHTTPError(AdminError):
18
+ """The site answered with an HTTP error status.
19
+
20
+ Attributes:
21
+ status_code: the HTTP status.
22
+ url: the URL that was requested.
23
+ """
24
+
25
+ def __init__(self, message: str, status_code: int, url: str) -> None:
26
+ super().__init__(message)
27
+ self.status_code = status_code
28
+ self.url = url
@@ -0,0 +1,310 @@
1
+ """A Django admin form, submitted the way a browser would submit it.
2
+
3
+ Load an add or change page, change values, add or delete inline rows, then submit.
4
+ Every field the page shows is sent back unchanged unless set, exactly like pressing
5
+ Save in the browser.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any, Dict, List, Optional, Tuple
11
+
12
+ from bs4 import Tag
13
+
14
+ from .exceptions import FormError, NotLoggedIn
15
+ from .parse import is_login_page, soup
16
+
17
+ SKIP_TYPES = {"submit", "button", "file", "image", "reset"}
18
+ _CONTROLS = ["input", "select", "textarea"]
19
+
20
+
21
+ def _textarea(el: Tag) -> str:
22
+ text = el.get_text()
23
+ return text[1:] if text.startswith("\n") else text
24
+
25
+
26
+ def _options(el: Tag) -> List[Tuple[str, str]]:
27
+ return [(o.get("value", ""), o.get_text(strip=True)) for o in el.find_all("option")]
28
+
29
+
30
+ def _kind(el: Tag) -> str:
31
+ if el.name == "select":
32
+ return "multiselect" if el.has_attr("multiple") else "select"
33
+ if el.name == "input":
34
+ return (el.get("type") or "text").lower()
35
+ return el.name
36
+
37
+
38
+ def _default_values(el: Tag) -> Optional[List[str]]:
39
+ """Values a browser would send for this control, None if it sends nothing."""
40
+ if el.has_attr("disabled"):
41
+ return None
42
+ if el.name == "textarea":
43
+ return [_textarea(el)]
44
+ if el.name == "select":
45
+ chosen = [o.get("value", "") for o in el.find_all("option") if o.has_attr("selected")]
46
+ if chosen or el.has_attr("multiple"):
47
+ return chosen
48
+ opts = el.find_all("option")
49
+ return [opts[0].get("value", "")] if opts else []
50
+ kind = (el.get("type") or "text").lower()
51
+ if kind in SKIP_TYPES:
52
+ return None
53
+ if kind in ("checkbox", "radio"):
54
+ return [el.get("value", "on")] if el.has_attr("checked") else []
55
+ return [el.get("value", "")]
56
+
57
+
58
+ class AdminForm:
59
+ """One admin add or change form.
60
+
61
+ Usually obtained from :meth:`AdminClient.form`. Field names are the HTML ``name``
62
+ attributes, so inline cells are addressed as ``<prefix>-<index>-<field>``.
63
+
64
+ Args:
65
+ client: an :class:`AdminClient` (anything with ``request``, ``post`` and
66
+ optionally ``base_url`` works).
67
+ path: path of the page, for example ``/admin/app/model/5/change/``.
68
+ text: HTML of the page if already fetched. If omitted the page is requested.
69
+
70
+ Attributes:
71
+ path: path of the page relative to the client's base URL.
72
+ fields: ``{name: [values]}`` exactly as they would be posted.
73
+ buttons: names of the submit buttons on the form.
74
+ messages: texts of the admin's message list (for example "... was changed successfully.").
75
+ errors: validation errors shown on the page.
76
+ """
77
+
78
+ def __init__(self, client: Any, path: str, text: Optional[str] = None) -> None:
79
+ self.client = client
80
+ self.path = self._relative(path)
81
+ if text is None:
82
+ url, text = client.request("GET", path)
83
+ self.path = self._relative(url)
84
+ self._parse(text)
85
+
86
+ def _relative(self, url: str) -> str:
87
+ """Strip the client's base URL so the path can be compared and posted back."""
88
+ base = (getattr(self.client, "base_url", "") or "").rstrip("/")
89
+ if base and (url == base or url.startswith((base + "/", base + "?"))):
90
+ rest = url[len(base):]
91
+ return rest if rest.startswith("/") else "/" + rest
92
+ return url
93
+
94
+ # ---------- parsing ----------
95
+ def _parse(self, text: str) -> None:
96
+ doc = soup(text)
97
+ if is_login_page(doc):
98
+ raise NotLoggedIn(f"{self.path} returned the login form: no session or it expired")
99
+ self.doc = doc
100
+ # The model form is the one with the most controls (pages can hold small helper forms too).
101
+ forms = [f for f in (doc.select("#content form") or doc.select("form"))
102
+ if f.find("input", attrs={"name": "csrfmiddlewaretoken"})]
103
+ form = max(forms, key=lambda f: len(f.find_all(_CONTROLS)), default=None)
104
+ self.form_count = len(forms)
105
+ self.form = form
106
+ self.fields: Dict[str, List[str]] = {}
107
+ self.kinds: Dict[str, str] = {}
108
+ self.choices: Dict[str, List[Tuple[str, str]]] = {}
109
+ self.templates: Dict[str, Dict[str, Tag]] = {}
110
+ self.buttons: List[str] = []
111
+ self._button_values: Dict[str, str] = {}
112
+ self.messages = [li.get_text(" ", strip=True) for li in doc.select("ul.messagelist li")]
113
+ self.errors = [e.get_text(" ", strip=True) for e in doc.select("p.errornote, ul.errorlist li")]
114
+ if form is None:
115
+ return
116
+ for el in form.find_all(_CONTROLS + ["button"]):
117
+ name = el.get("name")
118
+ if not name:
119
+ continue
120
+ kind = (el.get("type") or "").lower()
121
+ if kind == "submit" or (el.name == "button" and kind in ("", "submit")):
122
+ if name not in self.buttons:
123
+ self.buttons.append(name)
124
+ self._button_values[name] = el.get("value") or "1"
125
+ continue
126
+ if el.name == "button":
127
+ continue
128
+ m = re.match(r"(.+)-__prefix__-(.+)$", name)
129
+ if m:
130
+ self.templates.setdefault(m.group(1), {})[m.group(2)] = el
131
+ continue
132
+ vals = _default_values(el)
133
+ if vals is None:
134
+ continue
135
+ kind = _kind(el)
136
+ if kind in ("checkbox", "radio") and name in self.fields:
137
+ self.fields[name].extend(vals) # several boxes sharing one name
138
+ else:
139
+ self.fields[name] = vals
140
+ self.kinds[name] = kind
141
+ if el.name == "select":
142
+ self.choices[name] = _options(el)
143
+
144
+ # ---------- reading ----------
145
+ def has(self, name: str) -> bool:
146
+ """True if the form would post a field with this name (it is editable)."""
147
+ return name in self.fields
148
+
149
+ def get(self, name: str) -> Any:
150
+ """Current value: bool for a checkbox, list for a multiple select, else a string.
151
+
152
+ Returns None if the field is not editable on this page.
153
+ """
154
+ v = self.fields.get(name)
155
+ if v is None:
156
+ return None
157
+ if self.kinds.get(name) == "checkbox":
158
+ return bool(v)
159
+ if self.kinds.get(name) == "multiselect":
160
+ return list(v)
161
+ return v[0] if v else ""
162
+
163
+ def total(self, prefix: str) -> int:
164
+ """TOTAL_FORMS of an inline formset: saved rows plus rows added so far."""
165
+ return int(self.get(f"{prefix}-TOTAL_FORMS") or 0)
166
+
167
+ def initial(self, prefix: str) -> int:
168
+ """INITIAL_FORMS of an inline formset: rows already saved on the server."""
169
+ return int(self.get(f"{prefix}-INITIAL_FORMS") or 0)
170
+
171
+ def has_inline(self, prefix: str) -> bool:
172
+ """True if the page has an inline formset with this prefix."""
173
+ return f"{prefix}-TOTAL_FORMS" in self.fields
174
+
175
+ def row_text(self, prefix: str, index: int, field: str) -> Optional[str]:
176
+ """Displayed text of one inline cell: the selected option's label or the cell text."""
177
+ tr = self.doc.find(id=f"{prefix}-{index}")
178
+ td = tr.select_one(f".field-{field}") if tr else None
179
+ if td is None:
180
+ return None
181
+ sel = td.find("select")
182
+ if sel is not None:
183
+ o = sel.find("option", selected=True)
184
+ return o.get_text(strip=True) if o else None
185
+ return td.get_text(" ", strip=True)
186
+
187
+ def row_link_id(self, prefix: str, index: int, model: str) -> Optional[int]:
188
+ """Primary key from a link to ``.../<model>/<pk>/change/`` inside an inline row."""
189
+ tr = self.doc.find(id=f"{prefix}-{index}")
190
+ if tr is None:
191
+ return None
192
+ for a in tr.find_all("a", href=True):
193
+ m = re.search(rf"/{re.escape(model)}/(\d+)/change/", a["href"])
194
+ if m:
195
+ return int(m.group(1))
196
+ return None
197
+
198
+ def readonly(self, name: str) -> Optional[str]:
199
+ """Displayed text of a read-only field ("True", "False" or "None" for the bool icons).
200
+
201
+ This is the whitespace-collapsed text. Use :func:`parse_change_form` when the exact
202
+ stored value matters.
203
+ """
204
+ row = self.doc.select_one(f"div.form-row.field-{name} .readonly")
205
+ if row is None:
206
+ return None
207
+ img = row.find("img")
208
+ if img is not None and img.get("alt") in ("True", "False", "None"):
209
+ return img["alt"]
210
+ return row.get_text(" ", strip=True)
211
+
212
+ # ---------- writing ----------
213
+ def _resolve(self, name: str, value: Any) -> str:
214
+ """Accept an option value or its visible label for selects."""
215
+ value = "" if value is None else str(value)
216
+ opts = self.choices.get(name)
217
+ if opts is None:
218
+ return value
219
+ if any(v == value for v, _ in opts):
220
+ return value
221
+ for v, label in opts:
222
+ if label.lower() == value.lower():
223
+ return v
224
+ raise FormError(f"{name}: {value!r} is not a choice. Options: {[lb for _, lb in opts][:25]}")
225
+
226
+ def set(self, name: str, value: Any) -> None:
227
+ """Set a field.
228
+
229
+ Checkboxes take a truthy or falsy value. Selects take the option value or its
230
+ visible label (case-insensitive). Multiple selects take a list of those.
231
+ Raises FormError if the field is not editable or the choice does not exist.
232
+ """
233
+ if name not in self.fields:
234
+ raise FormError(f"field {name!r} is not editable on {self.path}")
235
+ kind = self.kinds[name]
236
+ if kind == "checkbox":
237
+ self.fields[name] = ["on"] if value else []
238
+ elif kind == "multiselect":
239
+ self.fields[name] = [self._resolve(name, v) for v in (value or [])]
240
+ else:
241
+ self.fields[name] = [self._resolve(name, value)]
242
+
243
+ def set_if_present(self, name: str, value: Any) -> bool:
244
+ """Set the field if it is editable here and value is not None. Returns whether it was set."""
245
+ if name in self.fields and value is not None:
246
+ self.set(name, value)
247
+ return True
248
+ return False
249
+
250
+ def add_row(self, prefix: str, values: Dict[str, Any]) -> int:
251
+ """Add a row to an inline formset and return its index.
252
+
253
+ The row is built from the formset's ``__prefix__`` empty-form template, so hidden
254
+ fields such as the parent key keep their defaults, and TOTAL_FORMS is increased.
255
+ ``values`` maps the short field names of the inline to values (see :meth:`set`).
256
+ """
257
+ tmpl = self.templates.get(prefix)
258
+ if tmpl is None or not self.has_inline(prefix):
259
+ raise FormError(f"inline {prefix!r} cannot take new rows on {self.path}")
260
+ maxn = int(self.get(f"{prefix}-MAX_NUM_FORMS") or 1000)
261
+ index = self.total(prefix)
262
+ if index >= maxn:
263
+ raise FormError(f"inline {prefix!r} is full (max {maxn})")
264
+ unknown = set(values) - set(tmpl)
265
+ if unknown:
266
+ raise FormError(f"inline {prefix!r} has no field(s) {sorted(unknown)}. Has: {sorted(tmpl)}")
267
+ for field, el in tmpl.items():
268
+ name = f"{prefix}-{index}-{field}"
269
+ vals = _default_values(el)
270
+ if vals is None:
271
+ continue
272
+ self.fields[name], self.kinds[name] = vals, _kind(el)
273
+ if el.name == "select":
274
+ self.choices[name] = _options(el)
275
+ if field in values:
276
+ self.set(name, values[field])
277
+ self.fields[f"{prefix}-TOTAL_FORMS"] = [str(index + 1)]
278
+ return index
279
+
280
+ def delete_row(self, prefix: str, index: int) -> None:
281
+ """Tick the DELETE box of a saved inline row. It is deleted when the form is submitted."""
282
+ self.set(f"{prefix}-{index}-DELETE", True)
283
+
284
+ def submit(self, button: str = "_continue") -> "AdminForm":
285
+ """POST the form by "pressing" the named submit button.
286
+
287
+ The default ``_continue`` is "Save and continue editing", which lands back on the
288
+ change page so the result can be inspected. ``_save`` and ``_addanother`` work too,
289
+ as do custom buttons the page defines.
290
+
291
+ Returns the page the admin answered with as a new AdminForm. Raises FormError if
292
+ the button does not exist or the admin reports validation errors. The POST is sent
293
+ once and never retried.
294
+ """
295
+ if self.form is None:
296
+ raise FormError(f"no form found on {self.path}")
297
+ if button not in self.buttons:
298
+ raise FormError(f"button {button!r} not on {self.path}. Has: {self.buttons}")
299
+ data = [(n, v) for n, vals in self.fields.items() for v in vals]
300
+ data.append((button, self._button_values.get(button, "1")))
301
+ url, text = self.client.post(self.path, data)
302
+ result = AdminForm(self.client, url, text)
303
+ if result.errors:
304
+ raise FormError(f"{self.path} rejected: {result.errors[:6]}")
305
+ return result
306
+
307
+ def object_id(self) -> Optional[int]:
308
+ """Numeric primary key from the page path, None on an add page."""
309
+ m = re.search(r"/(\d+)/change/", self.path)
310
+ return int(m.group(1)) if m else None
@@ -0,0 +1,233 @@
1
+ """Parsers for stock Django admin pages (change form and change list).
2
+
3
+ They rely only on the markup Django's own admin templates produce:
4
+
5
+ * change form: ``div.form-row.field-<name>`` holding an input, select, textarea or ``div.readonly``
6
+ * inlines: ``#<prefix>-group`` with ``tr.form-row.has_original`` and ``td.field-<name>``
7
+ (tabular) or ``div.inline-related.has_original`` (stacked)
8
+ * change list: ``#result_list tbody tr`` and the ``.paginator`` element
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import html
13
+ import re
14
+ from typing import Any, Dict, List, Optional, Union
15
+ from urllib.parse import parse_qs, urlparse
16
+
17
+ from bs4 import BeautifulSoup, Tag
18
+
19
+ _BOOL = {"True": True, "False": False, "None": None}
20
+ _CHANGE_LINK = re.compile(r"/([^/?#]+)/change/")
21
+
22
+
23
+ def soup(text: str) -> BeautifulSoup:
24
+ """Parse HTML with the standard library parser (no lxml needed)."""
25
+ return BeautifulSoup(text, "html.parser")
26
+
27
+
28
+ def is_login_page(doc: BeautifulSoup) -> bool:
29
+ """True if the page is the stock admin login form."""
30
+ return doc.select_one("#login-form") is not None
31
+
32
+
33
+ def _pk(text: str) -> Union[int, str]:
34
+ return int(text) if text.isdigit() else text
35
+
36
+
37
+ def decode_readonly(node: Tag) -> str:
38
+ """Recover the stored value from a read-only cell.
39
+
40
+ Django renders read-only text as ``linebreaksbr(escape(value))``. The stored value is
41
+ therefore: the inner HTML, with ``<br>`` turned back into a newline, HTML-unescaped
42
+ exactly once. Nothing is stripped, so leading spaces and trailing newlines survive.
43
+
44
+ A cell showing only "-" is Django's placeholder for an empty value and decodes to "".
45
+ """
46
+ inner = node.decode_contents()
47
+ inner = re.sub(r"<br\s*/?>", "\n", inner)
48
+ value = html.unescape(inner)
49
+ return "" if value.strip() == "-" else value
50
+
51
+
52
+ def _readonly_value(node: Tag) -> Any:
53
+ img = node.find("img")
54
+ if img is not None and img.get("alt") in _BOOL and not node.get_text(strip=True):
55
+ return _BOOL[img["alt"]]
56
+ links = node.find_all("a")
57
+ if links and node.get_text(strip=True) == "".join(a.get_text(strip=True) for a in links):
58
+ return {"text": node.get_text(" ", strip=True), "links": [a.get("href") for a in links]}
59
+ return decode_readonly(node)
60
+
61
+
62
+ def _widget_value(el: Tag) -> Any:
63
+ if el.name == "select":
64
+ chosen = [{"value": o.get("value", ""), "label": o.get_text(strip=True)}
65
+ for o in el.find_all("option") if o.has_attr("selected")]
66
+ if el.has_attr("multiple"):
67
+ return chosen
68
+ return chosen[0] if chosen else None
69
+ if el.name == "textarea":
70
+ text = el.get_text()
71
+ return text[1:] if text.startswith("\n") else text # browsers drop one leading newline
72
+ kind = el.get("type", "text")
73
+ if kind == "checkbox":
74
+ return el.has_attr("checked")
75
+ if kind == "file":
76
+ return None
77
+ return el.get("value", "")
78
+
79
+
80
+ def _cell(container: Tag) -> Optional[Dict[str, Any]]:
81
+ """Value of one field container (a form-row div, a fieldBox or an inline td)."""
82
+ split = [i for i in container.find_all("input") if re.search(r"_[01]$", i.get("name", ""))]
83
+ if len(split) == 2 and split[0].get("name", "")[:-2] == split[1].get("name", "")[:-2]:
84
+ parts = [i.get("value", "") for i in split] # Django's split date + time widget
85
+ return {"value": " ".join(x for x in parts if x), "readonly": False}
86
+ el = None
87
+ for cand in container.find_all(["input", "select", "textarea"]):
88
+ if cand.get("type") in ("hidden", "submit", "button"):
89
+ continue
90
+ el = cand
91
+ break
92
+ if el is not None:
93
+ out = {"value": _widget_value(el), "readonly": False}
94
+ if el.get("type") == "file":
95
+ link = container.find("a")
96
+ out["value"] = link.get("href") if link else None
97
+ return out
98
+ ro = container.find(class_="readonly") or container.find("p")
99
+ if ro is not None:
100
+ return {"value": _readonly_value(ro), "readonly": True}
101
+ return None
102
+
103
+
104
+ def _field_names(tag: Tag) -> List[str]:
105
+ return [cls[len("field-"):] for cls in tag.get("class", []) if cls.startswith("field-")]
106
+
107
+
108
+ def _row_cells(row: Tag) -> Dict[str, Dict[str, Any]]:
109
+ """Fields of one form row. A row holds several when the ModelAdmin groups fields on a line."""
110
+ names = _field_names(row)
111
+ out: Dict[str, Dict[str, Any]] = {}
112
+ if len(names) > 1:
113
+ for name in names:
114
+ box = next((b for b in row.find_all(class_="field-" + name)
115
+ if "fieldBox" in b.get("class", [])), None)
116
+ cell = _cell(box) if box is not None else None
117
+ if cell is not None:
118
+ out[name] = cell
119
+ if out:
120
+ return out
121
+ if names:
122
+ cell = _cell(row)
123
+ if cell is not None:
124
+ out[names[0]] = cell
125
+ return out
126
+
127
+
128
+ def parse_change_form(text: str) -> Dict[str, Any]:
129
+ """Parse the HTML of an admin add or change page.
130
+
131
+ Returns a dict with:
132
+
133
+ * ``fields``: ``{name: {"value": ..., "readonly": bool}}`` for every field row of the
134
+ main form. Values are: a string for text inputs and textareas, a bool for checkboxes,
135
+ ``{"value", "label"}`` for a select (a list of those for a multiple select, None if
136
+ nothing is selected), the current file URL or None for file inputs, "date time" for
137
+ the split date and time widget. Read-only fields give the recovered stored string,
138
+ a bool or None for the yes/no/unknown icons, or ``{"text", "links"}`` when the cell
139
+ is made of links only.
140
+ * ``inlines``: ``{prefix: [row, ...]}`` for each inline formset, saved rows only. Each
141
+ row maps field name to value (same value rules as above), plus ``id`` (the hidden
142
+ primary key, a string) and ``_links`` (``{model_name: pk}`` for every link in the
143
+ row that points at an admin change page).
144
+ * ``logged_out``: True if the page is the admin login form instead.
145
+ """
146
+ doc = soup(text)
147
+ content = doc.select_one("#content") or doc
148
+ fields: Dict[str, Dict[str, Any]] = {}
149
+ for row in content.select("div.form-row"):
150
+ if row.find_parent(class_="inline-group"):
151
+ continue
152
+ fields.update(_row_cells(row))
153
+
154
+ inlines: Dict[str, List[Dict[str, Any]]] = {}
155
+ for group in content.select(".inline-group"):
156
+ prefix = group.get("id") or ""
157
+ if prefix.endswith("-group"):
158
+ prefix = prefix[:-len("-group")]
159
+ rows = []
160
+ for tr in group.select("tr.form-row.has_original, div.inline-related.has_original"):
161
+ row: Dict[str, Any] = {}
162
+ hidden_id = tr.find("input", attrs={"name": re.compile(r"-\d+-id$")})
163
+ if hidden_id is not None:
164
+ row["id"] = hidden_id.get("value")
165
+ for td in tr.select("td[class*=field-], div.form-row[class*=field-]"):
166
+ names = _field_names(td)
167
+ cell = _cell(td)
168
+ if names and cell is not None:
169
+ row[names[0]] = cell["value"]
170
+ for a in tr.find_all("a", href=True):
171
+ m = re.search(r"/([a-z0-9_]+)/([a-z0-9_]+)/(\d+)/change/", a["href"])
172
+ if m:
173
+ row.setdefault("_links", {})[m.group(2)] = int(m.group(3))
174
+ rows.append(row)
175
+ inlines[prefix] = rows
176
+
177
+ return {"fields": fields, "inlines": inlines, "logged_out": is_login_page(doc)}
178
+
179
+
180
+ def field_value(form: Dict[str, Any], name: str, default: Any = None) -> Any:
181
+ """Shortcut for ``form["fields"][name]["value"]`` on a parsed change form."""
182
+ cell = form["fields"].get(name)
183
+ return default if cell is None else cell["value"]
184
+
185
+
186
+ def parse_changelist(text: str) -> Dict[str, Any]:
187
+ """Parse the HTML of one admin change list page.
188
+
189
+ Returns a dict with:
190
+
191
+ * ``ids``: primary keys of the rows on this page, in display order (int when numeric,
192
+ otherwise the string as it appears in the page).
193
+ * ``total``: the result count the paginator shows, or None if it could not be read.
194
+ * ``last_page``: number of the last page as labelled in the paginator (1 if there is
195
+ only one page).
196
+ * ``p_offset``: what to add to a page label to get its ``?p=`` value. Django's ``p``
197
+ is 0-based before 3.2 (offset -1) and 1-based from 3.2 on (offset 0); this is read
198
+ off the paginator links, so no Django version has to be configured.
199
+ * ``logged_out``: True if the page is the admin login form instead.
200
+ """
201
+ doc = soup(text)
202
+ ids: List[Union[int, str]] = []
203
+ for tr in doc.select("#result_list tbody tr"):
204
+ box = tr.find("input", attrs={"name": "_selected_action"})
205
+ if box is not None and box.get("value"):
206
+ ids.append(_pk(box["value"]))
207
+ continue
208
+ a = tr.find("a", href=_CHANGE_LINK)
209
+ if a is not None:
210
+ ids.append(_pk(_CHANGE_LINK.search(a["href"]).group(1)))
211
+ pag = doc.select_one(".paginator")
212
+ total = None
213
+ pages: Dict[int, int] = {}
214
+ last = 1
215
+ if pag is not None:
216
+ nums = re.findall(r"(\d[\d,]*)\s+[a-z]", pag.get_text(" ", strip=True))
217
+ if nums:
218
+ total = int(nums[-1].replace(",", ""))
219
+ for a in pag.find_all("a", href=True):
220
+ label = a.get_text(strip=True)
221
+ p = parse_qs(urlparse(a["href"]).query).get("p")
222
+ if label.isdigit() and p and p[0].isdigit():
223
+ pages[int(label)] = int(p[0])
224
+ current = pag.select_one(".this-page, [aria-current]")
225
+ if current is not None and current.get_text(strip=True).isdigit():
226
+ last = int(current.get_text(strip=True))
227
+ offset = 0
228
+ if pages:
229
+ label, p = next(iter(pages.items()))
230
+ offset = p - label
231
+ last = max(last, max(pages))
232
+ return {"ids": ids, "total": total, "last_page": last, "p_offset": offset,
233
+ "logged_out": is_login_page(doc)}
File without changes
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-admin-remote
3
+ Version: 0.1.0
4
+ Summary: Read and edit a remote Django admin site over HTTP by parsing its stock HTML. Nothing to install on the server.
5
+ Project-URL: Repository, https://github.com/krushndayshmookh/django-admin-remote
6
+ Project-URL: Issues, https://github.com/krushndayshmookh/django-admin-remote/issues
7
+ Project-URL: Changelog, https://github.com/krushndayshmookh/django-admin-remote/blob/main/CHANGELOG.md
8
+ Author: Krushn Dayshmookh
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: admin,automation,client,django,formset,inlines,scraping
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: Django
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: beautifulsoup4>=4.9
28
+ Requires-Dist: requests>=2.25
29
+ Requires-Dist: tzdata; sys_platform == 'win32'
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # django-admin-remote
35
+
36
+ Read and edit a remote Django admin site from Python, over plain HTTP, by parsing the HTML the stock admin already serves. Nothing is installed on the server: if you can use the admin in a browser, you can script it.
37
+
38
+ It is meant for the case where you have admin access to a Django site but no API and no way to deploy code to it.
39
+
40
+ - Reads change forms: editable fields, read-only fields (with the stored value recovered, not just the displayed text), yes/no icons, links, and inline formset rows.
41
+ - Reads change lists: ids, total count, all pages, with the same filters the admin puts in the URL.
42
+ - Submits add and change forms the way a browser does: every field is sent back, selects can be set by label, inline rows can be added and deleted, custom submit buttons can be pressed, validation errors are raised.
43
+ - Logs in with a username and password, or reuses the cookies of a browser session for sites behind SSO.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install django-admin-remote
49
+ ```
50
+
51
+ Python 3.10 or newer. Depends on `requests` and `beautifulsoup4`.
52
+
53
+ ## Quickstart
54
+
55
+ ```python
56
+ from django_admin_remote import AdminClient, FormError
57
+
58
+ admin = AdminClient("https://admin.example.com", delay=0.5)
59
+ admin.login("alice", "correct horse battery staple")
60
+
61
+ # ids of every matching row, across all pages of the change list
62
+ ids = list(admin.changelist("/admin/blog/post/", status__exact="draft", limit=50))
63
+
64
+ # read one object, including read-only fields and inline rows
65
+ post = admin.read(f"/admin/blog/post/{ids[0]}/change/")
66
+ print(post["fields"]["title"]["value"], post["inlines"]["comment_set"])
67
+ # change it like a browser would: untouched fields are sent back as they are
68
+ form = admin.form(f"/admin/blog/post/{ids[0]}/change/")
69
+ form.set("title", "A better title")
70
+ form.set("status", "Published") # a select: option value or visible label
71
+ form.add_row("comment_set", {"text": "First!"})
72
+ try:
73
+ saved = form.submit("_continue") # "Save and continue editing"
74
+ except FormError as err:
75
+ print("the admin rejected the form:", err)
76
+ ```
77
+
78
+ To create an object, load the add page (`admin.form("/admin/blog/post/add/")`), set the fields, submit, and read `saved.object_id()`.
79
+
80
+ ## Authentication
81
+
82
+ **Username and password.** `admin.login(username, password)` uses the standard admin login form at `/admin/login/` (change it with `login_path=`). The password is posted once and not kept.
83
+
84
+ **Existing cookies.** Sites that log in through SSO (Google, Okta and so on) have no password form to post to. Log in with a real browser once and hand the session cookies over:
85
+
86
+ ```python
87
+ admin = AdminClient("https://admin.example.com", cookies={"sessionid": "..."})
88
+ # or a Playwright storage_state file, as saved by context.storage_state(path="state.json")
89
+ admin = AdminClient("https://admin.example.com", storage_state="state.json")
90
+ ```
91
+
92
+ Playwright is not a dependency. Only the JSON file it writes is read, and only cookies whose domain matches the base URL are used.
93
+
94
+ When the session is missing or has expired the client raises `NotLoggedIn`. It notices this from a redirect to a login page or to another host, and from the login form showing up where an admin page was expected.
95
+
96
+ ## API overview
97
+
98
+ | Call | What it does |
99
+ | --- | --- |
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
+ | `client.login(username, password)` | Log in through the admin login form. |
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. |
104
+ | `client.changelist(path, limit=None, params=None, **filters)` | Iterator over the ids of a change list, all pages. |
105
+ | `client.read(path)` | `parse_change_form` of a page: `{"fields", "inlines", "logged_out"}`. |
106
+ | `client.form(path)` | An `AdminForm` for an add or change page. |
107
+ | `client.parse_datetime(text)` | `parse_admin_datetime` with the client's `tz`. |
108
+ | `AdminForm.has / get / set / set_if_present` | Read and change the values that will be posted. |
109
+ | `AdminForm.add_row(prefix, values) / delete_row(prefix, index)` | Inline formset rows. |
110
+ | `AdminForm.total(prefix) / initial(prefix) / row_text / row_link_id` | Inspect inline formsets. |
111
+ | `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
+ | `parse_change_form(html)`, `parse_changelist(html)` | The parsers, usable on HTML you fetched yourself. |
114
+ | `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`. |
116
+
117
+ Every public function and method has a docstring with the details.
118
+
119
+ ### Inline formsets
120
+
121
+ Inline fields are addressed by their HTML names, `<prefix>-<index>-<field>`. The prefix is what the admin uses in the page (often the related name, such as `comment_set`); look at `parse_change_form(...)["inlines"].keys()` to find it.
122
+
123
+ ```python
124
+ form = admin.form("/admin/blog/post/7/change/")
125
+ form.set("comment_set-0-text", "edited") # change a saved row
126
+ form.delete_row("comment_set", 1) # tick its DELETE box
127
+ index = form.add_row("comment_set", {"text": "new"}) # built from the empty-form template
128
+ form.submit()
129
+ ```
130
+
131
+ `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
+
133
+ ### Dates
134
+
135
+ The admin shows datetimes in the server's time zone without naming it. Pass the zone to get an unambiguous value:
136
+
137
+ ```python
138
+ from django_admin_remote import parse_admin_datetime
139
+ parse_admin_datetime("Sept. 29, 2026, 3:03 a.m.", "Europe/Paris") # '2026-09-29T03:03:00+02:00'
140
+ ```
141
+
142
+ ## How it reads read-only fields
143
+
144
+ An editable field carries its exact value in the HTML (`value="..."`, the textarea body, the selected option). A read-only field is only displayed, so the stored value has to be worked out from what Django rendered.
145
+
146
+ For plain values Django's admin renders a read-only field as `linebreaksbr(escape(value))`: the value is HTML-escaped, then every newline becomes `<br>`. The parser reverses exactly those two steps on the cell's inner HTML:
147
+
148
+ 1. `<br>` is turned back into a newline.
149
+ 2. The result is HTML-unescaped once.
150
+
151
+ The parser strips and collapses nothing. Whatever is in the cell comes back: inner newlines, a trailing newline, leading spaces, and a stored `a &lt; b` (text that itself contains an entity) as `a &lt; b` and not as `a < b`. Taking the visible text of the cell, as a generic scraper would, loses these.
152
+
153
+ One caveat is on Django's side. Newer Django versions strip leading and trailing whitespace from a read-only string before rendering it (seen on Django 6.1, where `display_for_value` calls `strip()`). On such a site the outer whitespace never reaches the HTML, so a stored `5\n` reads as `5`. Older versions render it in full. If exact outer whitespace matters, check what your site sends.
154
+
155
+ The other cases:
156
+
157
+ - The yes / no / unknown icons become `True`, `False` and `None`.
158
+ - A cell made only of links (a foreign key with a link, for example) becomes `{"text": ..., "links": [...]}`.
159
+ - A cell showing just `-` is Django's placeholder for an empty value and becomes `""`.
160
+
161
+ What cannot be recovered: anything the admin formats before display. Dates come back as displayed text (see `parse_admin_datetime`), numbers may be localized, foreign keys show the object's `str()`, and a read-only method that returns HTML through `format_html` or `mark_safe` comes back with that markup. A stored value that is literally `-` is indistinguishable from an empty one.
162
+
163
+ ## Limitations
164
+
165
+ - **It relies on stock admin markup.** The parsers look for the classes and ids Django's own templates produce (`form-row`, `field-<name>`, `readonly`, `inline-group`, `result_list`, `paginator`, `login-form`). Custom admin themes and replacement admin skins change that markup and may break parsing partly or completely. Check against your site before relying on it. The offline tests use markup saved from an older Django; a manual run against Django 6.1 (login, change list pages and filters, read, save, inline add and delete) also passed.
166
+ - **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
+ - **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
+ - **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
+ - No file uploads. File inputs are left out of the POST, which keeps the existing file.
170
+ - 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
+ - Change list parsing returns ids, the count and the pages, not the column values. Read each object for its data.
172
+ - The total count and the dates assume an English-language admin with default formats.
173
+ - Primary keys in `AdminForm.object_id()`, `row_link_id()` and inline `_links` are assumed to be integers.
174
+ - Admin actions (the dropdown above the change list) and the delete confirmation page are not wrapped. `client.get` and `client.post` are there if you need them.
175
+
176
+ ## Prior art
177
+
178
+ [`django-admin-client`](https://pypi.org/project/django-admin-client/) had the same idea first: a Python client for a Django admin site that works over HTTP. Its last release on PyPI is 0.2.4 from March 2019. It logs in with a username and password, offers list, get, add, change and delete, and can generate a client spec for a site. If that covers your case, look at it first.
179
+
180
+ `django-admin-remote` was written for things its documentation does not mention:
181
+
182
+ - inline formsets (read, add and delete rows),
183
+ - read-only fields with the stored value recovered,
184
+ - change list filters and pagination across pages, on both old and new Django page numbering,
185
+ - sessions from browser cookies, for admin sites behind SSO,
186
+ - custom submit buttons, and built-in request pacing.
187
+
188
+ On the other side, this package has no delete helper and no spec generation.
189
+
190
+ ## Development
191
+
192
+ ```bash
193
+ python -m pip install -e ".[test]"
194
+ python -m pytest -q
195
+ ```
196
+
197
+ The tests run offline against saved admin HTML and a fake HTTP transport.
198
+
199
+ ## License
200
+
201
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ django_admin_remote/__init__.py,sha256=OEzS8FjMU_9frW8A93vGbxvTPEKS5p2eXGLDjF1zAYA,655
2
+ django_admin_remote/client.py,sha256=L8akh5x6Is7uDvBwbDYQKUZvda5B1bU3E3y-hNna1As,13073
3
+ django_admin_remote/dates.py,sha256=UKGn8zjcG0CPXaSBeI_V6NCOPIXo1dC_LnrAP00uxAk,2480
4
+ django_admin_remote/exceptions.py,sha256=Q0U2xA3mZVXCQ4y6B88nopSel87zKMJBa5F7fWpfggs,797
5
+ django_admin_remote/form.py,sha256=hM8Pb_VYbU4Pj3T6PhwJCIJg7er-3Rr-Kqld4KdgA8U,13254
6
+ django_admin_remote/parse.py,sha256=THtV2D8UBBdIAEudSTv7O7mBR1C4TgV1P8TMPhmiLaY,9849
7
+ django_admin_remote/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ django_admin_remote-0.1.0.dist-info/METADATA,sha256=joUmdyDj6ZQykWzSOniUU1xB7xCsLly6jxFkL0csyng,12462
9
+ django_admin_remote-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ django_admin_remote-0.1.0.dist-info/licenses/LICENSE,sha256=zW0KjXhJmtNdWkmqNiCQ_uQbo0c2siYjcgDx49Gcppc,1074
11
+ django_admin_remote-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Krushn Dayshmookh
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.