Metadata-Version: 2.5
Name: django-htmx-calendar
Version: 0.4.0
Summary: A reusable Django calendar app with HTMX-powered navigation and recurring events.
Project-URL: Repository, https://github.com/taut-and-yare/django-htmx-calendar
Author-email: Taut and Yare <dev@yare.fr>
License: MIT
License-File: LICENSE
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Framework :: Wagtail
Classifier: Framework :: Wagtail :: 7
Classifier: Framework :: Wagtail :: 8
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.12
Requires-Dist: django-recurrence>=1.14
Requires-Dist: django>=5.2
Requires-Dist: pillow>=9.0
Provides-Extra: cms
Requires-Dist: django-cms>=5.0; extra == 'cms'
Provides-Extra: dev
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: pytest-django; extra == 'dev'
Requires-Dist: tox; extra == 'dev'
Requires-Dist: wagtail>=7.0; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest; extra == 'test'
Requires-Dist: pytest-cov; extra == 'test'
Requires-Dist: pytest-django; extra == 'test'
Provides-Extra: wagtail
Requires-Dist: wagtail>=7.0; extra == 'wagtail'
Description-Content-Type: text/markdown

# django-htmx-calendar

> 0.x releases may change templates and settings between minor versions. Read
> [CHANGELOG.md](CHANGELOG.md) before upgrading.

A reusable Django calendar app with HTMX-powered navigation, recurring events,
per-calendar status workflow, and an optional Wagtail integration.

## 1. What it is

`django-htmx-calendar` provides:

- Monthly, weekly, daily, and yearly calendar views
- Recurring events via `django-recurrence`
- Add, edit and delete events in a modal, plus a read-only event summary
  (date and time, location, description, photo)
- Per-calendar event status workflow (draft → pending → published)
- HTMX-powered navigation without full page reloads
- A pluggable permission system
- Optional Wagtail snippet and StreamField chooser block

## 2. Requirements

- Python 3.12, 3.13 or 3.14
- Django 5.2, 6.0 or 6.1
- HTMX, loaded in your base template (tested with HTMX 2)
- `django-recurrence` and Pillow, installed as dependencies
- Tailwind CSS 4 in your project, for now (see "Styling")
- Optional: Wagtail 7.0 to 8.0

The test suite runs in CI on six representative combinations of these
versions, listed in `tox.ini`.

## 3. Installation

```bash
pip install django-htmx-calendar
```

Add to `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    ...
    "django.contrib.sites",   # required
    "recurrence",
    "htmx_calendar",
]
```

Add the middleware that sets `request.site`:

```python
MIDDLEWARE = [
    ...
    "django.contrib.sites.middleware.CurrentSiteMiddleware",  # required
]
```

Include URLs, and the JavaScript catalog that the recurrence widget loads from
`/jsi18n/`:

```python
# urls.py
from django.urls import include, path
from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
    path("cal/", include("htmx_calendar.urls")),
]
```

Add the context processors (`request` is needed for permission checks in
templates):

```python
TEMPLATES = [{
    "OPTIONS": {
        "context_processors": [
            ...
            "django.template.context_processors.request",
            "htmx_calendar.context_processors.calendar",
        ],
    },
}]
```

Event photos are stored with your default storage under `events/`, so
`MEDIA_ROOT` and `MEDIA_URL` must be configured and served.

Run migrations:

```bash
python manage.py migrate
```

### Upgrading from 0.3.x

0.4.0 dropped two dependencies and moved the component templates. See
"Upgrading from 0.3.x" in [CHANGELOG.md](CHANGELOG.md).

### Upgrading from `calendrier` (0.1.x)

The app was renamed from `calendrier` to `htmx_calendar` in 0.2.0. Replace
`calendrier` with `htmx_calendar` in `INSTALLED_APPS`, URL includes, imports
and template paths, then run `migrate`: migration 0010 renames the database
tables and content types. Setting names have since moved to the `CALENDAR_` prefix; see the CHANGELOG.

## 4. Quick start

```python
from django.contrib.sites.models import Site
from htmx_calendar.models import Calendar

site = Site.objects.get_current()
Calendar.objects.create(site=site, name="My Events")
```

Visit `/cal/my-events/monthly/`.

## 5. Permissions

A policy decides who may view a calendar and who may add, edit, delete and
publish its events. The default lets everyone view and active staff do
everything else; staff also see unpublished events in the grids, marked.

Choose another policy in settings:

```python
CALENDAR_POLICY = "htmx_calendar.policy.ModelPermissionsPolicy"
```

`ModelPermissionsPolicy` follows Django's permissions on events (add, change,
delete, and "Can publish events"), which Wagtail's group permissions screen
can grant.

To write your own, subclass `CalendarPolicy`:

```python
from htmx_calendar.permissions import ACTION_EDIT_EVENT, ACTION_VIEW
from htmx_calendar.policy import CalendarPolicy


class AuthorsEditTheirOwn(CalendarPolicy):
    def can(self, user, action, calendar, event=None):
        if action == ACTION_VIEW:
            return True
        if action == ACTION_EDIT_EVENT and event is not None:
            return user.is_authenticated and event.created_by_id == user.pk
        return user.is_active and user.is_staff
```

`event` is passed for actions on an existing event. `can` is also asked with
`event=None` (for example `edit_event` from `visible_statuses`, `add_event`,
`view`), meaning "may the user do this on this calendar at all"; a policy
must handle it, or every grid render fails. `visible_statuses(user,
calendar)` decides which events a user sees: by default, users who may edit
see every status and others see published events only.

Actions (import from `htmx_calendar.permissions`): `ACTION_VIEW`,
`ACTION_ADD_EVENT`, `ACTION_EDIT_EVENT`, `ACTION_DELETE_EVENT`,
`ACTION_PUBLISH_EVENT`, `ACTION_APPROVE_EVENT`.

In templates:

```django
{% load cal_tags %}
{% calendar_can calendar "add_event" as can_add %}
{% calendar_can calendar "edit_event" event=event as can_edit %}
```

A visitor refused `view` is sent to the login page; a logged-in user gets
403.

### Who can see an event

By default an event is exactly as visible as its calendar. An event can be
given an audience of its own in the event form or the admin, which narrows
that: **Logged-in users**, or **Chosen groups** (logged-in users in at least
one of the event's groups). Users who may edit the calendar see every event,
with restricted ones marked. Outside its audience an event leaves no trace:
it is not in the grids, the "+N more" counts or the legend, and its URLs
answer 404.

The policy decides, with two methods you can override:

- `visible_memberships(user, calendar, memberships)` receives a queryset of
  the calendar's `EventInCalendar` rows and returns those `user` may see.
  The default applies `visible_statuses` and the audience rule above; return
  a narrowed queryset for any other rule.
- `audience_groups(calendar)` returns the groups the event form offers
  ("Chosen groups" appears only when it returns at least one). The default
  is every group (on Wagtail that includes its own admin groups,
  "Moderators" and "Editors", so a Wagtail site will usually override it); on
  a project with several sites, return each site's own:

```python
from django.contrib.auth.models import Group

from htmx_calendar.policy import DefaultPolicy


class SitePolicy(DefaultPolicy):
    def audience_groups(self, calendar):
        return Group.objects.filter(name__startswith=f"{calendar.site.domain}:")
```

### What the Wagtail admin manages

The Wagtail calendar and category snippets ask the policy too, with two
methods that receive the request:

- `admin_calendars(request)` returns the calendars `request` may manage. The
  listing, the chooser (used by `CalendarChooserBlock` and by page fields
  that point to a calendar) and bulk delete show only these calendars and
  their categories. Any view of another calendar or category, such as edit,
  delete or copy, answers 404. The default is the current site's calendars,
  `Calendar.objects.filter(site=request.site)`.
- `admin_sites(request)` returns the sites a calendar may be put on when
  `request` creates or edits it. The calendar form offers only these; when
  there is exactly one, it hides the field and puts the calendar on that
  site. The default is every site, so a project with one site never shows
  the field.

On a project where each editor looks after some sites:

```python
from django.contrib.sites.models import Site

from htmx_calendar.models import Calendar
from htmx_calendar.policy import DefaultPolicy


class SitePolicy(DefaultPolicy):
    """Editors manage the sites their groups name: "<domain>:editors"."""

    def admin_sites(self, request):
        names = request.user.groups.values_list("name", flat=True)
        domains = [n.removesuffix(":editors") for n in names if n.endswith(":editors")]
        return Site.objects.filter(domain__in=domains)

    def admin_calendars(self, request):
        return Calendar.objects.filter(site__in=self.admin_sites(request))
```

The chooser offers only `admin_calendars`, but a page field or StreamField
block still accepts any calendar id posted to it; narrow the page's form if
that matters. Wagtail's snippets index still counts every calendar.

## 6. Template customisation

Set your project's base template:

```python
CALENDAR_BASE_TEMPLATE = "myapp/base.html"
```

`htmx_calendar/base.html` extends it and fills three blocks: `extra_head`
(the package assets), `modal` (a `<dialog id="cal-dialog">` holding the
`#dialog` element the forms and event summary load into) and `content`.
If your base uses different block names, create
`templates/htmx_calendar/base.html` in your project and map them.

### Embedding the calendar in your own page

To show a calendar inside another page rather than on its standalone URL:

1. Load the assets and the form media in the page's head:
   `{% load cal_tags %}{% htmx_calendar_assets %}` and `{{ add_event_form.media }}`
   (build the form with `htmx_calendar.forms.AddEventForm(calendar=calendar)`).
2. Provide the modal: `<dialog id="cal-dialog"><div id="dialog"></div></dialog>`.
3. Load a grid into a placeholder:

   ```django
   <div hx-get="{% url 'htmx_calendar:monthly' calendar_slug='my-events' %}"
        hx-trigger="load"
        hx-swap="outerHTML"></div>
   ```

Or render it inline, without a lazy load (steps 1 and 2 still apply):

```django
{% load cal_tags %}
{% render_calendar calendar view="monthly" set="compact" %}
```

`view` and `set` are optional. The tag needs `request` in the context and
renders nothing when the visitor may not view the calendar or when the view
is not offered. Navigation inside the grid keeps the set.

### Template sets

Every piece of the UI is a package template with a short name, its file
name: `monthly_grid`, `monthly_day`, `monthly_day_events`, `monthly_bars`
(a month row's bars of events lasting a day or more), `timegrid_event` (an
event of the week and day views' hours), `allday_row` (their row of events
lasting a day or more), `event_bar` (one such bar), `header_section`,
`label_legend`, `label_filter`, `event_detail`, `modal_form`, `form_field`,
… A **template set** replaces some of them for the calendars that use it,
and only those:

1. Register it: `CALENDAR_TEMPLATE_SETS = {"renaud": "Renaud"}`.
2. Put the replacements in any template directory, under
   `htmx_calendar/sets/renaud/<name>.html`. A template the set does not hold
   falls back to the package's.
3. Choose the set per calendar (the calendar's "template set" field), per
   project (`CALENDAR_RULES` or `CALENDAR_DEFAULTS`), or per embed
   (`{% render_calendar calendar set="renaud" %}`, or `?set=renaud` on a
   grid URL).

A set file can also change a single part of a package template by
extending it:

```django
{# htmx_calendar/sets/renaud/monthly_day_events.html #}
{% extends "htmx_calendar/components/monthly_day_events.html" %}
{% block event_line %}<span class="dot"></span>{{ block.super }}{% endblock event_line %}
```

Blocks available: `event_line` and `cell_body` (month cells),
`header_left` and `header_right` (grid header), `form_footer` (event form).

A set file that replaces one of `monthly_grid`, `weekly_grid`, `daily_grid`,
`yearly_grid` (on the outer `<div>`), `event_detail` (on the `<article>`) or
`modal_form` (on the `<form>`) whole must keep this attribute on the same
element:

```django
{% if cal_embed_vals %}hx-vals="{{ cal_embed_vals }}"{% endif %}
```

It is what makes every HTMX request sent from inside an embedded calendar
repeat the embed's set. Extending the package template and replacing a block
keeps it automatically. It relies on htmx attribute inheritance, htmx's
default; a host that sets `htmx.config.disableInheritance` must add
`hx-inherit="hx-vals hx-include"` on those elements.

A set replacing `event_detail` whole should also keep the links to an event's
source and the Delete button of an orphan event: the context variables
`source_url`, `source_edit_url`, `source_missing` and `can_delete`.

The four grid roots also keep this line, which keeps the selected labels
during navigation:

```django
{% if cal_label_groups %}hx-include="#{{ calendar.slug }}-{{ view_mode }}-grid [data-cal-label-filter]"{% endif %}
```

and `data-cal-grid`, by which the package stylesheet dims a grid while it
fetches the next one. A set replacing `prev`, `next` or `today` keeps the
button's `id` (`{{ calendar.slug }}-prev`, `-next`, `-today`): htmx gives
the focus back to it after the swap.

The month grid is laid out in week rows: `monthly_grid` loops over `weeks`,
each with its `days`, `bars` and `lanes`, and includes `monthly_bars` in a
row that has bars. A day's list is `d.shown_events` (its events shorter than
a day, as many as fit beside the bars) with `d.more_count` left over; a set
replacing `monthly_day_events` whole uses them, and keeps the list's top
margin of `week.lanes` lines so the bars do not cover it. `d.events` still
holds every event of the day.

A set replacing `header_section` whole keeps its last line, which includes
`label_filter` or `label_legend` as the calendar's `label_display` says
(section 8).

The header's links take their URLs from the context: `prev_url`, `next_url`
and `today_url`, and `cal_view_urls`, each offered view with the URL that
opens it on the grid's date, as `(view, url)` pairs. A set replacing `prev`,
`next`, `today`, `mode_toggle` or `header_section` uses them. A view opens on
the day the day view shows; from a week, month or year, on today when the
period holds it, else on its first day.

A replacement of `event_form_fields` keeps the
`{% for field in form.label_fields %}` loop with its `labels_shown` hidden
marker; without it, editors cannot set labels, and labels are left as they are.
It also keeps the audience block, inside `{% if can_edit %}`: `form.audience`
and the `data-cal-show-if-groups` wrapper around `form.audience_groups_field`.

The grids' event elements mark restricted events for editors with
`{% if cal_can_edit and <event>.audience %}data-cal-audience="{{ <event>.audience }}"{% endif %}`
(`cal_can_edit` is a context variable); a replacement of a grid keeps it, or
editors see restricted events looking public.

Inside package templates, components are pulled in with
`{% cal_include "<name>" %}`, which follows the calendar's set; use it in
your set files too. A template you put at a package path itself (e.g.
`htmx_calendar/components/monthly_day.html`, in a template directory that
comes before `htmx_calendar`) still overrides it for every calendar.

### Styling

This describes 0.4.0 and is expected to change in a later release.

The calendar's templates are written with Tailwind CSS 4 utility classes and a
theme colour named `accent`. A host project needs:

1. Tailwind CSS 4.
2. An `accent` colour in its theme, for example:

   ```css
   @theme {
     --color-accent: #2563eb;
   }
   ```

3. The package's templates among the files Tailwind scans. Print their
   location:

   ```bash
   python -c "import htmx_calendar, pathlib; print(pathlib.Path(htmx_calendar.__file__).parent / 'templates')"
   ```

   and name that directory as a source in your stylesheet, as a path relative
   to the stylesheet:

   ```css
   @source "../path/to/site-packages/htmx_calendar/templates";
   ```

The event form is the exception: the package stylesheet styles it, and it
needs no Tailwind.

### The days of the month and year grids

When the calendar offers the day view, a day of the month grid opens it:
tapped on a phone, clicked or entered on a desktop. Links to events inside a
day stop their click there. On a phone, where a day has no room for its
events, a dot marks a day that has some. Without a day view, a phone's day
with events and "+N more" open the day's events in the modal (`day_events`,
a template a set can replace), each leading to its summary.

In the year grid, a dot marks each day that has events, and a day opens the
most detailed view the calendar offers: the day, else its week, else its
month. A month's name opens the month view. The days a month's grid borrows
from its neighbours carry no dot or tint: their own month shows them.

These attributes are there for your own CSS, so you can restyle without
replacing a template:

| Attribute | On |
|---|---|
| `data-cal-day` | each day cell (the month grid's phone button and desktop cell, the year grid's day, the day columns behind the week and day views' hours) |
| `data-cal-day-dot` | the dot of a day with events (month grid on a phone, year grid) |
| `data-cal-unavailable` | a day holding an unavailable event, and each unavailable event, in every grid |
| `data-cal-grid` | each grid's root; dimmed while it fetches the next grid |

The package stylesheet tints an unavailable day lightly, with zero
specificity, so any rule of yours wins:

```css
[data-cal-day][data-cal-unavailable] { background-color: #fb7185; color: #fff; }
[data-cal-day][data-cal-unavailable] [data-cal-day-dot] { background-color: #fff; }
```

## 7. Options per calendar

Each calendar has seven options. Editors set them on the calendar in the
Django admin or the Wagtail snippet; a project can set them in code. For each
option the first value found wins:

1. the embed (a template tag or block that renders the calendar),
2. the calendar's own field, when not blank (editors see blank as "Project
   default" in a menu, or no box ticked in a list),
3. `CALENDAR_RULES`, a function `(calendar) -> dict` in your code,
4. `CALENDAR_DEFAULTS`, a dict in settings,
5. the package default.

| Option | Meaning | Package default |
|---|---|---|
| `views` | Views offered: `monthly`, `weekly`, `daily`, `yearly` | all four |
| `default_view` | Where `/cal/<calendar slug>/` leads | `monthly` |
| `template_set` | A registered template set (section 6) | none |
| `label_providers` | Label providers, in order (section 8) | `categories` |
| `label_display` | Above the grid: nothing (`none`), the colour legend (`legend`), or the legend with its filter (`filter`) (section 8) | `none` |
| `visible_start_hour` | The hour the week and day views' time grid starts at, `0` to `23` | `0` |
| `visible_end_hour` | The hour that time grid ends at, `1` to `24` | `24` |

The view switcher lists only the offered views and disappears when there is
one; other views answer 404.

The week and day views show every hour by default. With, say,
`{"visible_start_hour": 8}`, they start at 08:00: an event that overlaps the
hours shows the part inside them, one wholly outside them is not shown. When
the two hours make no day (the start at or after the end), every hour is
shown and a warning is logged.

A project without editors can use code only:

```python
# settings.py
CALENDAR_DEFAULTS = {"views": ["monthly", "daily"]}
CALENDAR_RULES = "myproject.calendar.rules"
```

```python
# myproject/calendar.py
def rules(calendar):
    if calendar.site.domain == "festival.example":
        return {"default_view": "daily"}
    return {}
```

Because the calendar's own field comes before `CALENDAR_RULES`, an editor can
override a rule. When an option belongs to code alone, for example a template
set and the views it was designed for, leave it out of
`CALENDAR_EDITABLE_OPTIONS`:

```python
CALENDAR_EDITABLE_OPTIONS = ["label_providers", "label_display"]
```

The admin and the Wagtail snippet then offer only those options, and the
calendar's stored value for the others is not read, so `CALENDAR_RULES` and
`CALENDAR_DEFAULTS` decide them. The embed still comes first. By default
every option is editable.

## 8. Labels

Events can carry **labels** (categories, tags, …). The calendar colours an
event by its first coloured label and lists an event's labels in its
summary. What appears above the grid is the calendar's `label_display`
(section 7): nothing by default; with `legend`, the labels and their
colours; with `filter`, the same legend with checkboxes that filter the
grid. The legend appears only when the calendar has labels. It lists only
labels carried by at least one event the visitor can see.

With `filter`, filtering happens on the server: choosing labels re-fetches
the grid shown with `label=<key>` repeated, and navigating keeps the
selection. Labels of one group (e.g. two categories) combine with OR; labels
of different groups (a category and a tag) with AND. Without `filter`, a
request's `label=` values are ignored.

### Categories

The built-in `categories` provider is on by default. Categories belong to a
calendar: create them in the Django admin or the Wagtail "Event categories"
snippets, with an optional colour (`#rrggbb`) and an order. Editors choose
an event's categories in the event form.

### Your own labels

A label provider supplies a calendar's labels from anywhere, for example a
tag model in your own app:

```python
from htmx_calendar.labels import Label, LabelProvider

from myapp.models import EventTag


class TagProvider(LabelProvider):
    verbose_name = "Tags"

    def _label(self, tag):
        return Label(key=f"tag:{tag.slug}", name=tag.name, colour=tag.colour, group="Tag")

    def labels(self, calendar):
        return [self._label(t) for t in EventTag.objects.filter(site=calendar.site)]

    def labels_for_events(self, calendar, event_ids):
        found = {}
        links = EventTag.events.through.objects.filter(event_id__in=event_ids)
        for link in links.select_related("eventtag"):
            found.setdefault(link.event_id, []).append(self._label(link.eventtag))
        return found

    def filter_events(self, calendar, events, keys):
        slugs = [k.removeprefix("tag:") for k in keys if k.startswith("tag:")]
        return events.filter(eventtag__slug__in=slugs).distinct()
```

Register it, then list it in a calendar's label providers (section 7):

```python
CALENDAR_LABEL_PROVIDERS = {"tags": "myapp.labels.TagProvider"}
```

`labels_for_events` must use a fixed number of queries, whatever the number
of events. To let editors set the labels in the event form, also implement
`form_field(calendar)`, `initial(calendar, event)` and
`save(calendar, event, value)`; the field appears as `labels_<name>`.

### Styling

Event elements carry `data-cal-labels="<keys>"` and, when a label has a
colour, the CSS variable `--cal-event-colour`. The package stylesheet draws
a bar on the event's leading edge and a swatch in the legend; override
`[data-cal-labels]` and `[data-cal-label]` to change them.

## 9. Events from other apps

Another app can put its own objects in a calendar (a blog post that is also
an event, …), with no calendar UI. The app owns the data and calls the
package from its own code; the calendar follows.

```python
from htmx_calendar.api import remove_event, save_event

save_event(
    post,
    calendars=[calendar],
    title=post.title,
    start=post.event_start,
    duration=90,            # minutes
    location=post.place,
)
remove_event(post)          # when the post is withdrawn or deleted
```

- Each event remembers its source: calling `save_event` again updates the
  same event, in exactly the calendars given (all of one site).
  `event_for(source)` finds it.
- Events made this way are **published** in their calendars (publishing the
  source is the approval), have no description, and are **read-only in the
  calendar**: their summary has a "Read more" link to the source and, for
  editors, an Edit link to the source's editor; the calendar's own edit and
  delete refuse them. Edits made to them in the Django admin are overwritten
  at the next `save_event`. An event whose source no longer exists (an
  orphan) can be deleted from its summary, by those who may delete events.
- The source key is the source's concrete model and pk: remove events with the
  same class you saved them with. Saves made by host code with
  `update_fields` are not synced (by design: Wagtail uses them for drafts).
- `categories=[slugs]` sets their categories (`None`, the default, leaves
  them); `audience=` and `audience_groups=` set who can see them (section 5).
  A label provider over your own tags labels them with no extra code.
- The source names its links with two optional methods:
  `get_calendar_event_url(request)` (else `get_absolute_url()` is used) and
  `get_calendar_event_edit_url(request)`.

### Wagtail pages

```python
from wagtail.models import Page

from htmx_calendar.wagtail_mixins import CalendarEventPageMixin


class BlogPage(CalendarEventPageMixin, Page):
    content_panels = [
        *Page.content_panels,
        *CalendarEventPageMixin.calendar_event_panels,
    ]
```

The mixin adds a "Calendar" panel (calendar, start, end, place; make a
migration). A page with a calendar and a start is in that calendar while it
is live: publishing (including scheduled publishing and workflow approval)
adds or updates its event, unpublishing and deleting remove it, and drafts
never reach the calendar. The page's privacy setting gives the event's
audience (logged-in users, groups; a password-protected page is visible to
editors only). Override `get_calendar_event_data()` to change what is sent,
e.g. to map tags to categories. Page aliases get no event of their own (the
original's event stands for both).

Some Wagtail operations change a page without going through its `save()`:
scheduled expiry, the admin's bulk unpublish, privacy changes, moving a page
under a restricted section, and bulk updates. Run
`manage.py sync_calendar_events` regularly to re-sync every page that uses
the mixin, in the same cron **after** `publish_scheduled`; it is safe to run
at any time.

The mixin's calendar field lists every calendar. On a project with several
sites, give the page a form that offers only the calendars of the page's site
(on creation, of its parent's site). This example assumes each django `Site`'s
domain is the matching Wagtail site's hostname:

```python
from wagtail.admin.forms import WagtailAdminPageForm
from wagtail.models import Page

from htmx_calendar.models import Calendar
from htmx_calendar.wagtail_mixins import CalendarEventPageMixin


class BlogPageForm(WagtailAdminPageForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        page = self.instance if self.instance.pk else self.parent_page
        site = page.get_site() if page else None
        if site and "event_calendar" in self.fields:
            self.fields["event_calendar"].queryset = Calendar.objects.filter(
                site__domain=site.hostname,
            )


class BlogPage(CalendarEventPageMixin, Page):
    base_form_class = BlogPageForm
```

## 10. django CMS

The django CMS plugin is not maintained at present and is not tested. It was
last tested with 0.3.1. The code is still in the package (`cms_plugins.py`,
the `cms` extra).

## 11. Wagtail integration

```bash
pip install "django-htmx-calendar[wagtail]"
```

`Calendar` and `EventCategory` are registered as Wagtail snippets. The policy
decides which of them the admin shows, by default the current site's, and
which sites a calendar may be put on: see
[What the Wagtail admin manages](#what-the-wagtail-admin-manages).

Add a calendar to any StreamField:

```python
from htmx_calendar.wagtail_blocks import CalendarChooserBlock

body = StreamField([("calendar", CalendarChooserBlock())])
```

**Known limitation**: block-level validation cannot access the parent page's
site. The render-time `calendar_permission_required` check is the final
safety net for cross-site data.

## 12. Development

```bash
make dev            # first-time setup: create .venv (Python 3.12+), migrate and seed the sandboxes
make serve          # plain sandbox at http://localhost:8000/cal/demo/monthly/
make serve-wagtail  # Wagtail sandbox at http://localhost:8000/cal/demo/monthly/
make test           # core and Wagtail suites in the dev virtualenv
make test-matrix    # every supported Python/Django/Wagtail combination, through tox
```

Run `make help` for the full list of targets.

## 13. Settings reference

| Setting | Type | Default | Description |
|---|---|---|---|
| `CALENDAR_BASE_TEMPLATE` | template name | `"base.html"` | Template that `htmx_calendar/base.html` extends |
| `CALENDAR_POLICY` | dotted path | `htmx_calendar.policy.DefaultPolicy` | The permission policy class |
| `CALENDAR_DEFAULTS` | dict | `{}` | Project defaults for the options of section 7 |
| `CALENDAR_RULES` | dotted path | `None` | Function `(calendar) -> dict` of options |
| `CALENDAR_EDITABLE_OPTIONS` | list | every option | Options of section 7 that editors may set on a calendar |
| `CALENDAR_TEMPLATE_SETS` | dict | `{}` | Registered template sets, name → label |
| `CALENDAR_LABEL_PROVIDERS` | dict | `{}` | Registered label providers, name → class path |
