11 KiB
Ntfy blueprint for a Django tasks and health tracker
This is a portable version of this project's /settings integration. It gives each user a topic URL, a test button, an enable switch, and one function that task or health code can call. Replace accounts with the app that owns your user preferences. The examples assume an authenticated /settings/ page and Django's standard CSRF and messages middleware.
1. Store preferences
In accounts/models.py (merge these fields into an existing per-user settings model if you have one):
from django.conf import settings
from django.db import models
class NotificationSettings(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ntfy_url = models.URLField(blank=True)
ntfy_enabled = models.BooleanField(default=False)
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
Run python manage.py makemigrations accounts and python manage.py migrate.
2. Add the sender
Create notifications/services.py (and an empty notifications/__init__.py if needed):
import socket
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
class NotificationError(Exception):
"""A delivery error safe to display to a user."""
def send_ntfy_notification(url, title, message, timeout=10):
request = Request(
url,
data=message.encode("utf-8"),
headers={"Content-Type": "text/plain; charset=utf-8", "Title": title},
method="POST",
)
try:
with urlopen(request, timeout=timeout) as response:
status = response.getcode()
except HTTPError as error:
raise NotificationError(f"ntfy server responded with HTTP {error.code}.") from error
except (TimeoutError, socket.timeout):
raise NotificationError("Connection to the ntfy server timed out.") from None
except URLError as error:
raise NotificationError("Could not connect to the ntfy server.") from error
except OSError as error:
raise NotificationError("Could not connect to the ntfy server.") from error
if not 200 <= status < 300:
raise NotificationError(f"ntfy server responded with HTTP {status}.")
def send_notification(user, title, message):
from accounts.models import NotificationSettings
preferences = NotificationSettings.objects.filter(user=user).first()
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
return False
send_ntfy_notification(preferences.ntfy_url, title, message)
return True
The URL is a destination and may contain a private topic name. Keep it out of logs and error messages. A user supplied server URL also lets the server make outbound requests; restrict destinations or allow only your trusted ntfy host if your deployment needs that boundary. Add authentication headers if your ntfy server requires them; this example uses a topic URL only.
3. Form, views, and routes
In accounts/forms.py:
from django import forms
from .models import NotificationSettings
class NotificationSettingsForm(forms.ModelForm):
class Meta:
model = NotificationSettings
fields = ["ntfy_url", "ntfy_enabled"]
widgets = {"ntfy_url": forms.URLInput(attrs={"id": "ntfy-url", "placeholder": "https://ntfy.example.com/my-topic"})}
def clean_ntfy_url(self):
return self.cleaned_data["ntfy_url"].strip()
def clean(self):
data = super().clean()
if data.get("ntfy_enabled") and not data.get("ntfy_url"):
self.add_error("ntfy_url", "Enter a topic URL before enabling notifications.")
return data
In accounts/views.py:
from hashlib import sha256
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.decorators.http import require_POST
from notifications.services import NotificationError, send_ntfy_notification
from .forms import NotificationSettingsForm
from .models import NotificationSettings
def test_key(user):
return f"ntfy_tested_url_fingerprint:{user.pk}"
def fingerprint(url):
return sha256(url.encode("utf-8")).hexdigest()
@login_required
def settings_page(request):
preferences, _ = NotificationSettings.objects.get_or_create(user=request.user)
old_url = preferences.ntfy_url
form = NotificationSettingsForm(request.POST or None, instance=preferences)
if request.method == "POST" and form.is_valid():
url = form.cleaned_data["ntfy_url"]
just_tested = bool(url) and request.session.get(test_key(request.user)) == fingerprint(url)
previously_tested = url == old_url and preferences.ntfy_last_tested_at is not None
if form.cleaned_data["ntfy_enabled"] and not (just_tested or previously_tested):
form.add_error("ntfy_url", "Test this URL successfully before enabling notifications.")
else:
preferences = form.save(commit=False)
if not url:
preferences.ntfy_enabled = False
preferences.ntfy_last_tested_at = None
elif just_tested:
preferences.ntfy_last_tested_at = timezone.now()
elif url != old_url:
preferences.ntfy_last_tested_at = None
preferences.save()
request.session.pop(test_key(request.user), None)
messages.success(request, "Notification settings saved.")
return redirect("settings_page")
return render(request, "accounts/settings.html", {"form": form})
@login_required
@require_POST
def test_ntfy(request):
url = request.POST.get("ntfy_url", "").strip()
try:
URLValidator(schemes=["http", "https"])(url)
except ValidationError:
return render(request, "accounts/ntfy_test_result.html", {"error": "Enter a valid HTTP or HTTPS topic URL."}, status=400)
try:
send_ntfy_notification(url, "Tasks & Health", "Test notification sent successfully.")
except NotificationError as error:
return render(request, "accounts/ntfy_test_result.html", {"error": str(error)}, status=502)
request.session[test_key(request.user)] = fingerprint(url)
return render(request, "accounts/ntfy_test_result.html", {"success": True})
In accounts/urls.py, include these routes under /settings/ in the project URLconf:
from django.urls import path
from . import views
urlpatterns = [
path("", views.settings_page, name="settings_page"),
path("notifications/ntfy/test/", views.test_ntfy, name="ntfy_test"),
]
4. Settings UI
Put this section inside your existing /settings/ template. It uses htmx for the inline test response; load htmx once in the page layout (or replace hx-post with a small fetch handler). Keep the CSRF input inside the form.
<form method="post" action="{% url 'settings_page' %}">
{% csrf_token %}
<section aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Use a topic URL from your ntfy server. Test it before enabling notifications.</p>
<label for="ntfy-url">Topic URL</label>
{{ form.ntfy_url }} {{ form.ntfy_url.errors }}
<div class="check">
{{ form.ntfy_enabled }}
<label for="{{ form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label>
</div>
<button type="button" hx-post="{% url 'ntfy_test' %}"
hx-include="#ntfy-url, [name='csrfmiddlewaretoken']"
hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
<div id="ntfy-test-result" aria-live="polite"></div>
</section>
<button type="submit">Save settings</button>
</form>
<script>
document.querySelector("#ntfy-url").addEventListener("input", () => {
document.querySelector("#ntfy-test-result").replaceChildren();
});
</script>
accounts/ntfy_test_result.html:
{% if success %}<div class="alert alert--success">✓ Test notification sent successfully.</div>
{% else %}<div class="alert alert--error">Could not send the test notification: {{ error }}</div>{% endif %}
Suggested CSS, scoped to your existing settings styles:
#ntfy-url { width: 100%; box-sizing: border-box; min-height: 2.8rem; }
.check { display: flex; gap: .6rem; align-items: center; }
.check label { margin: 0; }
.alert { margin-top: 1rem; padding: .75rem; border-radius: .55rem; }
.alert--success { color: #d1fae5; background: #14532d; }
.alert--error { color: #fee2e2; background: #7f1d1d; }
5. Trigger from tasks or health events
Call the provider agnostic send_notification after a meaningful state change. Put delivery on a background worker for normal operation, since the HTTP call can take up to ten seconds. Queue the job after the database commit so it cannot announce a rolled back change.
from django.db import transaction
# After saving a task completion, missed deadline, check-in, or health alert:
user_id = task.user_id
task_id = task.pk
transaction.on_commit(lambda: enqueue_task_event_notification(user_id, task_id))
enqueue_task_event_notification is your existing Celery, RQ, or job queue entry point. In its worker, reload the user and task, confirm that the event still qualifies, then call send_notification(user, "Task due", "Your task is due today."). Catch NotificationError, log a safe error without the topic URL, and retry according to your queue policy. Use an event ID or unique job key if duplicate delivery matters. If you have no worker yet, a management command run by cron can drain a small notification outbox instead.
Typical mapping for this app:
| App event | Suggested message | Trigger location |
|---|---|---|
| Task due | “Your task is due today.” | Scheduled due-date job |
| Task completed | “Task completed.” | Completion service, after commit |
| Check-in missed | “Your daily check-in is still open.” | Scheduled reminder job |
| Health threshold crossed | “A tracked value crossed your chosen threshold.” | Threshold evaluator, after commit |
Avoid including sensitive health measurements in the notification unless the user explicitly opts in. Define the event's recipient and idempotency rule in the app service, rather than in the ntfy sender.
6. Minimum verification
Test an invalid URL, a failed test, a successful test followed by save, a changed URL requiring a new test, and disabled settings suppressing sends. Mock urlopen or send_ntfy_notification; do not send real notifications in tests. Check one actual device delivery manually with a private topic before enabling event triggers.
Source implementation in this repo: members/views.py, members/forms.py, members/models.py, members/templates/members/user_settings.html, notifications/services.py, and fireworks_detect/signals.py. The source app groups Pending events by minute with PendingNotificationBatch and a scheduled command; use that pattern if your tracker needs digest notifications.