Skip to content

Allow insert_model / after_model_change to control the create response #1029

@dhcsousa

Description

@dhcsousa

Checklist

  • There are no similar issues or pull requests for this yet.

Is your feature related to a problem? Please describe.

Problem

When overriding insert_model in a ModelView, the create handler in application.py always issues a 302 redirect after a successful insert:

obj = await model_view.insert_model(request, form_data_dict)
url = self.get_save_redirect_url(...)
return RedirectResponse(url=url, status_code=302)

There is no way for a ModelView to stay on the create page or render a custom response after a successful create. The after_model_change hook returns None and cannot influence the HTTP response.

The only current workaround is to raise an exception from insert_model, which abuses exception-based control flow and causes the exception to be logged via logger.exception(e) in the create handler's except block, which makes no sense at all.

Use Case

One-time secret display after creating a resource (similar to how GitHub, and other platforms handle token creation). This is a common pattern for any admin who manages secrets, tokens, or credentials:

  1. Admin creates an API key
  2. The generated secret is shown once on the create page with a copy button
  3. After navigating away, the secret is never shown again

Related Issues

#971 is somehow related. However, flash messages are designed for transient notifications shown on the next page after a redirect. A one-time secret needs to:

  • Stay on the current page (no redirect)
  • Be displayed prominently and persistently (not auto-dismissing)
  • Include a copy-to-clipboard button
  • Only disappear when the user explicitly navigates away

Describe the solution you would like.

Make the return value of after_model_change meaningful. Currently, it always returns None. Instead, allow it to return:

  • None - default redirect (fully backward-compatible)
  • dict - re-render the create/edit template with extra context merged in
  • Response - return a custom Starlette Response directly

Describe alternatives you considered

  • Raising an exception from insert_model to prevent the redirect - works but abuses control flow and pollutes logs via logger.exception(e)
  • Flash messages ( Add toast to notify results for custom actions #971 ) - insufficient for one-time secret display since they redirect and auto-dismiss

Additional context

No response

I will happily contribute to this and give it a try.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions