rustango 0.40.0

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! View-side helpers shared across handlers — model lookup, FK join
//! composition, FK display-value mapping, list-cell rendering, form
//! rendering, and pager URL composition.

use std::collections::HashMap;
use std::fmt::Write as _;

use crate::core::{inventory, FieldSchema, Join, ModelEntry, ModelSchema, Relation};
#[allow(unused_imports)]
use crate::sql::sqlx;

use super::render;
#[allow(unused_imports)]
use super::templates::render_template;
use super::urls::AppState;

/// Map of `(target_table, source_value_string) → display_value_html`.
/// Populated from joined rows so list/detail rendering needs no extra
/// per-FK queries.
pub(crate) type FkMap = HashMap<(String, String), String>;

/// Iterate the model inventory, deduplicating entries that share a SQL
/// table name. When two models point at the same `table`, the one with
/// **more fields** wins; ties resolve to the first inventory order.
///
/// This is what makes a project-side override like
/// [`crate::tenancy::TenantUserModel`] visible to the admin even when
/// the framework's own model is also registered for the same table —
/// e.g. `AppUser` (9 fields) shadows the framework's `User` (7 fields)
/// on `rustango_users`. The richer schema is also what we want for
/// list/detail rendering since the user explicitly added columns by
/// declaring it.
pub(crate) fn inventory_entries_dedup_by_table() -> Vec<&'static ModelEntry> {
    let mut by_table: indexmap::IndexMap<&'static str, &'static ModelEntry> =
        indexmap::IndexMap::new();
    for entry in inventory::iter::<ModelEntry> {
        let table = entry.schema.table;
        match by_table.get(table) {
            Some(existing) if existing.schema.fields.len() >= entry.schema.fields.len() => {
                // Existing is at least as rich — keep it.
            }
            _ => {
                by_table.insert(table, entry);
            }
        }
    }
    by_table.into_values().collect()
}

/// Build the standard chrome context (sidebar + active-link state)
/// that every admin page renders. Pass the active table (or `None` on
/// the index page) so the matching sidebar link gets `class="active"`.
///
/// Brand fields are layered: `brand_name` falls back to `admin_title`
/// (set by [`crate::admin::Builder::title`]) which falls back to
/// `"Rustango Admin"`. Same chain for `brand_tagline` → `admin_subtitle`.
/// Logos / theme mode / per-tenant CSS overrides come straight off
/// the config — they're set per-request by the tenancy admin from
/// the resolved [`crate::tenancy::Org`].
pub(crate) fn chrome_context(state: &AppState, active_table: Option<&str>) -> serde_json::Value {
    // #253 slice B — pick up the request-scoped AdminSession via
    // the task-local installed by `require_session`. Falling back
    // to `None` when called outside an admin request keeps
    // non-admin chrome callers (tests, hand-rendered pages) working.
    let session = super::session::current();
    chrome_context_with_session(state, active_table, session.as_ref())
}

/// As [`chrome_context`] but takes an explicit `Option<&AdminSession>`.
/// Used by tests and any path that has the session in hand directly
/// (without going through the task-local). #253 slice B.
pub(crate) fn chrome_context_with_session(
    state: &AppState,
    active_table: Option<&str>,
    session: Option<&super::session::AdminSession>,
) -> serde_json::Value {
    let admin_title = state.config.title.as_deref().unwrap_or("Rustango Admin");
    let brand_name = state.config.brand_name.as_deref().unwrap_or(admin_title);
    let brand_tagline = state
        .config
        .brand_tagline
        .as_deref()
        .or(state.config.subtitle.as_deref());
    serde_json::json!({
        "sidebar_groups": sidebar_context(state, active_table),
        "active_table": active_table.unwrap_or(""),
        "admin_title": admin_title,
        "admin_subtitle": state.config.subtitle.as_deref(),
        "brand_name": brand_name,
        "brand_tagline": brand_tagline,
        "brand_logo_url": state.config.brand_logo_url.as_deref(),
        "theme_mode": state.config.theme_mode.as_deref().unwrap_or("auto"),
        "tenant_brand_css": state.config.tenant_brand_css.as_deref(),
        // v0.27.8 (#78) — impersonation banner. Templates render
        // an unmissable warning when this is non-null so the
        // operator can't accidentally mutate tenant data while
        // forgetting they're impersonating.
        "impersonated_by_operator_id": state.config.impersonated_by,
        // v0.27.9 (#59) — URL prefix the admin Router is mounted
        // under. Templates use `{{ admin_prefix }}{{ audit_url }}` etc.
        // so hrefs resolve correctly regardless of mount path.
        "admin_prefix": &state.config.admin_prefix,
        // v0.30.19 — URL prefix for embedded static assets
        // (logo + favicon). Templates use {{ static_url }}/icon.png
        // for favicons.
        "static_url": &state.config.static_url,
        // Audit-log path suffix. Threaded from
        // `RouteConfig::audit_url`; default `/__audit` for
        // standalone admins. Templates compose the full
        // audit URL as `{{ admin_prefix }}{{ audit_url }}`.
        "audit_url": &state.config.audit_url,
        // v0.28.2 (#77) — sidebar "Change password" link target.
        // Threaded from the tenant admin's RouteConfig.
        "change_password_url": &state.config.change_password_url,
        // #253 — Logout button visibility. The bare admin's
        // session middleware redirects unauthenticated requests to
        // `/login`, so by the time chrome renders we know any
        // visitor is logged in. Templates show the button when
        // `session_user` is non-null. Tenancy admins thread their
        // own session info through a parallel path; this signal is
        // only set when the bare admin's `with_session_auth` is on.
        // #253 slice B — per-user chrome info. When a request-bound
        // `AdminSession` is available the sidebar renders "Signed in
        // as <username>" + the (superuser) badge. When session auth
        // is configured but no session was threaded (e.g. older
        // callers using the bare `chrome_context`), fall back to
        // just `authenticated: true` so the Logout button still
        // renders.
        "session_user": match (session, state.config.session_secret.is_some()) {
            (Some(s), _) => serde_json::json!({
                "authenticated": true,
                "username": s.username,
                "is_superuser": s.is_superuser,
            }),
            (None, true) => serde_json::json!({ "authenticated": true }),
            (None, false) => serde_json::Value::Null,
        },
    })
}

/// Build the sidebar context — every visible model the admin exposes,
/// grouped by Django-shape app label. Pass `active_table` so the
/// matching link gets `class="active"`.
///
/// Sidebar shape mirrors the operator console's left rail
/// (`tenancy/templates/op_layout.html`) so tenant operators see a
/// consistent navigation surface across both consoles.
pub(crate) fn sidebar_context(
    state: &AppState,
    active_table: Option<&str>,
) -> Vec<serde_json::Value> {
    let mut entries: Vec<&'static ModelEntry> = inventory_entries_dedup_by_table()
        .into_iter()
        // v0.27.7 — filter registry-scoped models out of tenant
        // admins (Org / Operator etc. don't live in the tenant
        // pool and must not surface in the tenant sidebar).
        .filter(|e| state.scope_visible(e.schema.scope))
        .filter(|e| state.is_visible(e.schema.table))
        .collect();
    entries.sort_by_key(|e| e.schema.name);

    let mut by_app: indexmap::IndexMap<String, Vec<&'static ModelEntry>> =
        indexmap::IndexMap::new();
    for e in entries {
        let label = e
            .resolved_app_label()
            .map_or_else(|| "Project".to_owned(), str::to_owned);
        by_app.entry(label).or_default().push(e);
    }
    let mut groups: Vec<(String, Vec<&'static ModelEntry>)> = by_app.into_iter().collect();
    groups.sort_by(|a, b| match (a.0.as_str(), b.0.as_str()) {
        ("Project", _) => std::cmp::Ordering::Greater,
        (_, "Project") => std::cmp::Ordering::Less,
        _ => a.0.cmp(&b.0),
    });

    groups
        .into_iter()
        .map(|(label, items)| {
            let models: Vec<serde_json::Value> = items
                .into_iter()
                .map(|e| {
                    serde_json::json!({
                        "name": e.schema.name,
                        "table": e.schema.table,
                        "active": active_table == Some(e.schema.table),
                    })
                })
                .collect();
            serde_json::json!({ "app": label, "models": models })
        })
        .collect()
}

/// Resolve `table` to a `ModelSchema`, but only if the admin is configured
/// to expose it. A model that exists but is filtered out via `show_only`
/// returns `None` here, which surfaces to users as a 404 — same response
/// as a genuinely missing table.
pub(crate) fn lookup_model(state: &AppState, table: &str) -> Option<&'static ModelSchema> {
    if !state.is_visible(table) {
        return None;
    }
    let entry = inventory_entries_dedup_by_table()
        .into_iter()
        .find(|e| e.schema.table == table)?;
    // v0.27.7 — apply the same scope filter the sidebar / index do
    // so a curious user typing `/__admin/rustango_orgs` directly
    // gets a 404 instead of leaking cross-tenant data via
    // search_path on schema-mode tenants.
    if !state.scope_visible(entry.schema.scope) {
        return None;
    }
    Some(entry.schema)
}

/// Build one [`Join`] per FK / O2O column on `model` whose target is
/// visible and has a display field. The join's `project` carries only
/// the target's display column — that's all the admin renders.
pub(crate) fn build_fk_joins(state: &AppState, model: &'static ModelSchema) -> Vec<Join> {
    let mut joins = Vec::new();
    for field in model.scalar_fields() {
        let Some(rel) = field.relation else { continue };
        let (to, on) = match rel {
            Relation::Fk { to, on } | Relation::O2O { to, on } => (to, on),
        };
        let Some(target) = lookup_model(state, to) else {
            continue;
        };
        let Some(display_field) = target.display_field() else {
            continue;
        };
        let alias = field.name;
        joins.push(Join {
            target,
            // `field.name` is a valid SQL identifier and unique within
            // the model (it's a Rust struct field), so it makes a
            // clean alias.
            alias,
            kind: crate::core::JoinKind::Left,
            // `<main>.<fk_col> = <alias>.<target_pk>` expressed as a
            // WhereExpr now that Join's `on_local`/`on_remote` shape
            // was generalized in issue #80.
            on: crate::core::WhereExpr::ExprCompare {
                lhs: crate::core::Expr::AliasedColumn {
                    alias: model.table,
                    column: field.column,
                },
                op: crate::core::Op::Eq,
                rhs: crate::core::Expr::AliasedColumn { alias, column: on },
            },
            project: vec![display_field.column],
        });
    }
    joins
}

/// Walk a row set produced with `joins` set, and for each row build the
/// `(target_table, source_value_string) → display_html` map entry. Rows
/// where the joined display value is `NULL` (LEFT JOIN miss — target row
/// not present) are skipped, so `render_cell` falls back to the raw value.
///
/// v0.37 — PG-typed back-compat; admin internals call
/// [`fk_map_from_joined_rows_json`] which works on any backend.
#[cfg(feature = "postgres")]
#[allow(dead_code)] // back-compat surface; live callers go through the `_json` variant.
pub(crate) fn fk_map_from_joined_rows(
    state: &AppState,
    model: &'static ModelSchema,
    rows: &[sqlx::postgres::PgRow],
) -> FkMap {
    let mut map: FkMap = HashMap::new();
    for field in model.scalar_fields() {
        let Some(rel) = field.relation else { continue };
        let to = match rel {
            Relation::Fk { to, .. } | Relation::O2O { to, .. } => to,
        };
        let Some(target) = lookup_model(state, to) else {
            continue;
        };
        let Some(display_field) = target.display_field() else {
            continue;
        };
        for row in rows {
            let Some(source) = render::read_value_as_string(row, field) else {
                continue;
            };
            let Some(display) = render::read_joined_value_as_html(row, field.name, display_field)
            else {
                continue;
            };
            map.insert((to.to_owned(), source), display);
        }
    }
    map
}

/// Build a `&q=…&<field>=<v>…` tail for prev/next pager URLs so the
/// active search and filters survive page navigation. Each value is
/// percent-encoded via a tiny ASCII-safe escaper good enough for the
/// admin's expected inputs.
pub(crate) fn pager_suffix(q: Option<&str>, filters: &[(&'static str, String)]) -> String {
    let mut out = String::new();
    if let Some(qs) = q {
        out.push_str("&q=");
        out.push_str(&url_encode(qs));
    }
    for (k, v) in filters {
        out.push('&');
        out.push_str(k);
        out.push('=');
        out.push_str(&url_encode(v));
    }
    out
}

/// Minimal URL-encoder for ASCII inputs. Escapes characters that have
/// special meaning in a query string. Multibyte UTF-8 is percent-encoded
/// byte-by-byte — Postgres handles the bytes the same on the way back.
fn url_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for byte in s.bytes() {
        let safe = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
        if safe {
            out.push(byte as char);
        } else {
            let _ = write!(out, "%{byte:02X}");
        }
    }
    out
}

/// Render one cell. For FK columns this resolves to a link into the target
/// table; everything else delegates to [`render::render_value`].
///
/// v0.37 — PG-typed back-compat; admin internals call
/// [`render_cell_json`] which works on any backend.
#[cfg(feature = "postgres")]
#[allow(dead_code)] // back-compat surface; live callers go through the `_json` variant.
pub(crate) fn render_cell(
    row: &sqlx::postgres::PgRow,
    field: &FieldSchema,
    fk_map: &FkMap,
) -> String {
    if let Some(rel) = field.relation {
        let to = match rel {
            Relation::Fk { to, .. } | Relation::O2O { to, .. } => to,
        };
        let Some(raw_value) = render::read_value_as_string(row, field) else {
            return "<em>NULL</em>".to_owned();
        };
        let raw_esc = render::escape(&raw_value);
        let to_esc = render::escape(to);
        return match fk_map.get(&(to.to_owned(), raw_value)) {
            Some(display) => format!(r#"<a href="/{to_esc}/{raw_esc}">{display}</a>"#),
            // Target hidden by show_only or row genuinely missing — show raw.
            None => raw_esc,
        };
    }
    render::render_value(row, field)
}

/// v0.37 — JSON-bridge counterpart of [`fk_map_from_joined_rows`]. Walks a
/// `Vec<serde_json::Value>` (one row per Value) instead of `Vec<PgRow>`,
/// using the dialect-agnostic `*_json` reader companions. Same output
/// shape: `(target_table, source_value_string) → display_html`.
pub(crate) fn fk_map_from_joined_rows_json(
    state: &AppState,
    model: &'static ModelSchema,
    rows: &[serde_json::Value],
) -> FkMap {
    let mut map: FkMap = HashMap::new();
    for field in model.scalar_fields() {
        let Some(rel) = field.relation else { continue };
        let to = match rel {
            Relation::Fk { to, .. } | Relation::O2O { to, .. } => to,
        };
        let Some(target) = lookup_model(state, to) else {
            continue;
        };
        let Some(display_field) = target.display_field() else {
            continue;
        };
        for row in rows {
            let Some(source) = render::read_value_as_string_json(row, field) else {
                continue;
            };
            let Some(display) =
                render::read_joined_value_as_html_json(row, field.name, display_field)
            else {
                continue;
            };
            map.insert((to.to_owned(), source), display);
        }
    }
    map
}

/// v0.37 — JSON-bridge counterpart of [`render_cell`]. Same FK-link
/// resolution logic, but reads the row through `serde_json::Value`
/// so it compiles + runs against any backend.
pub(crate) fn render_cell_json(
    row: &serde_json::Value,
    field: &FieldSchema,
    fk_map: &FkMap,
) -> String {
    if let Some(rel) = field.relation {
        let to = match rel {
            Relation::Fk { to, .. } | Relation::O2O { to, .. } => to,
        };
        let Some(raw_value) = render::read_value_as_string_json(row, field) else {
            return "<em>NULL</em>".to_owned();
        };
        let raw_esc = render::escape(&raw_value);
        let to_esc = render::escape(to);
        return match fk_map.get(&(to.to_owned(), raw_value)) {
            Some(display) => format!(r#"<a href="/{to_esc}/{raw_esc}">{display}</a>"#),
            None => raw_esc,
        };
    }
    render::render_value_json(row, field)
}

/// Render a create or edit form via the `form.html` template. Pre-fill
/// values come from `prefill` (keyed by Rust field name); pass `None` for
/// an empty create form. `pk_locked` makes the PK input read-only (edit
/// mode). `error_msg`, when present, is shown above the form.
///
/// `state` is needed so the sidebar context can be attached.
pub(crate) fn render_form(
    state: &AppState,
    model: &'static ModelSchema,
    prefill: Option<&HashMap<String, String>>,
    pk_locked: bool,
    error_msg: Option<&str>,
) -> String {
    render_form_with_inlines_and_pickers(
        state,
        model,
        prefill,
        pk_locked,
        error_msg,
        Vec::new(),
        &[],
    )
}

#[allow(clippy::too_many_arguments)]
fn render_form_with_inlines_and_pickers(
    state: &AppState,
    model: &'static ModelSchema,
    prefill: Option<&HashMap<String, String>>,
    pk_locked: bool,
    error_msg: Option<&str>,
    inline_panels: Vec<super::inlines::InlineFormPanel>,
    gfk_picker_cts: &[crate::contenttypes::ContentType],
) -> String {
    // v0.31.1 (#5): respect `state.config.admin_prefix` instead of
    // hardcoding `/__admin`. Apps on the v0.29+ friendly default
    // (`/admin`) were getting form-action URLs that 404'd.
    let admin_prefix = state.config.admin_prefix.as_str();
    let (action, edit_pk) = if pk_locked {
        let pk_field = model.primary_key().expect("pk_locked requires a PK");
        let pk_value = prefill
            .and_then(|m| m.get(pk_field.name).cloned())
            .unwrap_or_default();
        (
            format!(
                "{admin_prefix}/{}/{}",
                model.table,
                render::escape(&pk_value)
            ),
            Some(pk_value),
        )
    } else {
        (format!("{admin_prefix}/{}", model.table), None)
    };
    let title = if pk_locked {
        format!("Edit {}", model.name)
    } else {
        format!("New {}", model.name)
    };

    let admin_cfg = model
        .admin
        .copied()
        .unwrap_or(crate::core::AdminConfig::DEFAULT);

    // #244 — collect every `generic_fk(...)` `ct_column` so the row
    // closure can swap a raw integer input for a ContentType `<select>`
    // when that column is being rendered. Empty when the model has no
    // `generic_fk` declarations OR the caller didn't pre-load the CT
    // list — both cases fall through to `render_input`'s default.
    let gfk_ct_columns: std::collections::HashSet<&'static str> = if gfk_picker_cts.is_empty() {
        std::collections::HashSet::new()
    } else {
        model
            .generic_relations
            .iter()
            .map(|gr| gr.ct_column)
            .collect()
    };

    let row_for_field = |f: &'static FieldSchema| -> serde_json::Value {
        let value = prefill
            .and_then(|m| m.get(f.name))
            .map_or("", String::as_str);
        let is_readonly_field = admin_cfg.readonly_fields.iter().any(|n| *n == f.name);
        let extra = if f.primary_key {
            " <small>(pk)</small>"
        } else if is_readonly_field {
            " <small>read-only</small>"
        } else if f.auto {
            " <small>auto</small>"
        } else if gfk_ct_columns.contains(f.column) {
            " <small>generic FK</small>"
        } else if !f.nullable {
            " <small>required</small>"
        } else {
            ""
        };
        // PK is locked on edit; readonly_fields are locked on edit.
        // Auto fields are always locked — they're DB-assigned.
        let lock_input = f.auto || (pk_locked && (f.primary_key || is_readonly_field));
        // #244 — swap raw integer input for a ContentType `<select>`
        // on fields named as a `generic_fk` ct_column.
        let input_html = if gfk_ct_columns.contains(f.column) {
            render::render_gfk_select(f, value, lock_input, gfk_picker_cts)
        } else {
            render::render_input(f, value, lock_input)
        };
        serde_json::json!({
            "label": f.name,
            "extra": extra,
            "input": input_html,
            // Django-shape `help_text` (#admin-helptext) — short
            // caption rendered under the input. `None` means no
            // caption; template treats it as falsy and renders nothing.
            "help_text": f.help_text,
        })
    };

    let visible = |f: &&'static FieldSchema| -> bool {
        // Auto fields (Auto<T> PK, auto_now_add, auto_uuid, default=…
        // server-assigned columns) are hidden on create — Postgres'
        // DEFAULT fills them. On edit they are shown readonly so the
        // operator can see the value.
        if f.auto && !pk_locked {
            // Hide auto fields entirely on the create form.
            return false;
        }
        true
    };

    // Optionally group fields into fieldsets (slice 10.5). Empty
    // fieldsets means "one unnamed group with every visible field".
    let fieldsets_ctx: Vec<serde_json::Value> = if admin_cfg.fieldsets.is_empty() {
        let rows: Vec<serde_json::Value> = model
            .scalar_fields()
            .filter(visible)
            .map(row_for_field)
            .collect();
        vec![serde_json::json!({ "title": "", "rows": rows })]
    } else {
        admin_cfg
            .fieldsets
            .iter()
            .map(|set| {
                let rows: Vec<serde_json::Value> = set
                    .fields
                    .iter()
                    .filter_map(|name| model.field(name))
                    .filter(visible)
                    .map(row_for_field)
                    .collect();
                serde_json::json!({ "title": set.title, "rows": rows })
            })
            .collect()
    };

    let inline_form_panels_ctx: Vec<serde_json::Value> = inline_panels
        .into_iter()
        .map(|p| serde_json::to_value(p).unwrap_or(serde_json::Value::Null))
        .collect();

    let mut ctx = serde_json::json!({
        "model": { "name": model.name, "table": model.table },
        "title": title,
        "action": action,
        "edit_pk": edit_pk,
        "error": error_msg,
        "fieldsets": fieldsets_ctx,
        "inline_form_panels": inline_form_panels_ctx,
    });
    super::templates::render_with_chrome(
        "form.html",
        &mut ctx,
        chrome_context(state, Some(model.table)),
    )
}

/// As [`render_form`] but threads a list of `InlineFormPanel` and a
/// pre-loaded `ContentType` list into the form context. The first
/// drives inline panel rendering (#50, slice 2); the second drives
/// the `generic_fk` `<select>` picker (#244). Used by `edit_form` and
/// `create_form` — pass an empty `inline_panels` from create-form
/// (Django's create-form-doesn't-render-inlines behavior).
pub(crate) fn render_form_with_inlines_and_picker(
    state: &AppState,
    model: &'static ModelSchema,
    prefill: Option<&HashMap<String, String>>,
    pk_locked: bool,
    error_msg: Option<&str>,
    inline_panels: Vec<super::inlines::InlineFormPanel>,
    gfk_picker_cts: &[crate::contenttypes::ContentType],
) -> String {
    render_form_with_inlines_and_pickers(
        state,
        model,
        prefill,
        pk_locked,
        error_msg,
        inline_panels,
        gfk_picker_cts,
    )
}