Metadata-Version: 2.4
Name: cached-markdown-field
Version: 1.0.0
Summary: Cached Markdown field for Django and django-markdownx
Keywords: django,cache,markdown,field
Author: Petr Hála
Author-email: Petr Hála <phala@sprtovo.eu>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Framework :: Django :: 5.1
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: django>=4.2
Requires-Dist: django-markdownx>=4.0
Requires-Python: >=3.10
Project-URL: Repository, https://github.com/pehala/cached-markdown-field
Project-URL: Changelog, https://github.com/pehala/cached-markdown-field/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/pehala/cached-markdown-field/issues
Description-Content-Type: text/markdown

# CachedMarkdownField for Django Models

A [django-markdownx](https://github.com/neutronX/django-markdownx) field that stores the rendered HTML in a column of
its own, so the Markdown is not rendered again on every request.

## Installation

```shell
uv add cached-markdown-field
```

Add `cached_markdown_field` to `INSTALLED_APPS` to get the `prerender` command.

## Example

```python
from cached_markdown_field.models import CachedMarkdownField


class Article(models.Model):
    description = CachedMarkdownField(verbose_name="Description", help_text="Markdown")


article = Article(description="*text*")
assert article.description == "*text*"
assert article.description_html == "<p><em>text</em></p>"
```

```django
{{ article.description_html|safe }}
```

The field is a `MarkdownxField`, so forms edit the Markdown with the markdownx editor. It adds a second, hidden column
with the HTML, `description_cached`; name it yourself with `cache_field`:

```python
text = CachedMarkdownField(cache_field="prerendered")
```

The column is created by the field, so do not declare it on the model; it appears in migrations like any other field.

### When is the HTML rendered?

- when the Markdown of an instance changes (assignment, forms),
- by the first save of an instance with the HTML column, so a changed compiler is picked up; later saves of the same
  instance render again only if the Markdown changed in between,
- when the HTML is read but missing, see `MARKDOWN_CACHE_RUNTIME`; this stores the HTML only if the row still holds the
  Markdown that was rendered.

Loading rows (and `refresh_from_db()`) renders nothing. `QuerySet.update()` and `bulk_update()` skip rendering; run
`python manage.py prerender` afterwards. Assigning an expression such as `F("text")` renders nothing either; the row's HTML is
cleared and rendered when it is read after `refresh_from_db()`.

`save(update_fields=[...])` stores only what it lists, and a field cannot add its HTML column to the list. Name the
column too, or the stored HTML no longer matches the Markdown; this emits a `RuntimeWarning`. A model loaded with
`only()` or `defer()` that leaves out the HTML column does the same, so keep it loaded when you change the Markdown.

The field replaces an attribute named `<name>_html` on the model; the system check `cached_markdown_field.E002`
reports one that you defined yourself.

## Compiler

By default the Markdown is rendered by `MARKDOWNX_MARKDOWNIFY_FUNCTION`, the function the markdownx editor preview
uses, so the preview shows what will be stored. A field can use its own one, as a callable or its dotted path:

```python
text = CachedMarkdownField(compiler="songs.markdown.render")
```

The compiler is looked up on every rendering, so it may pick its renderer from settings. After changing it, render the
stored rows again:

```shell
python manage.py prerender               # every model with a CachedMarkdownField
python manage.py prerender songs.Song    # only some models
python manage.py prerender --batch-size 200   # rows stored per query, 1000 by default
```

or from code; `prerender` returns the rows whose HTML changed, e.g. to clear caches of them:

```python
from cached_markdown_field.prerender import prerender

changed = prerender(Song.objects.all())
```

`prerender` stores the rows in batches while it reads them, and raises `ValueError` for a field name the model does not
have. `iter_prerender` yields the changed rows instead of collecting them.

## Settings

```python
# Store the rendered HTML; when False, the HTML is rendered on every read and the column is left alone
MARKDOWN_CACHE = True

# Render and store HTML that is missing when it is read; when False, reading it raises ValueError
MARKDOWN_CACHE_RUNTIME = True
```

## Upgrading from 0.1

0.1 was a composite field: `obj.description` returned the HTML and the Markdown was stored in
`description_markdown`. In 1.0 the Markdown column is `description` itself. Do not let `makemigrations` guess: it
would drop `description_markdown` and add an empty `description`. First write a migration which only renames it
(`python manage.py makemigrations --empty yourapp`):

```python
operations = [
    migrations.RenameField("article", "description_markdown", "description"),
]
```

then run `makemigrations` for the rest; it only changes the field class, which leaves the data alone.

`description_cached` keeps its name. In code and templates, read the HTML from `description_html`.

Finally run `python manage.py prerender`. 0.1 stored the HTML rendered twice, and treated an empty HTML as
missing, so the rows it cached hold wrong HTML until they are rendered again.

## Development

```shell
uv run pytest
uv run ruff check . && uv run ruff format --check .
```

To build the package locally, run `uv build`. It writes the sdist and the wheel to `dist/`:

```shell
uv build
```

To publish the built files from your machine, use a PyPI API token (trusted publishing only works in the release
workflow). Try it on TestPyPI first if you like:

```shell
uv publish --token <token>
uv publish --publish-url https://test.pypi.org/legacy/ --token <testpypi-token>
```

You can also pass the token through the `UV_PUBLISH_TOKEN` environment variable. Releasing by tag is preferred, see
below.

To release, tag the commit with the new version and push the tag. The workflow sets the version from the tag, so
there is nothing to edit:

```shell
git tag 1.2.3 && git push origin 1.2.3
```

The release workflow runs the tests, publishes to PyPI with trusted publishing and creates the GitHub release with
generated notes.
