# 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): ```python 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): ```python 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`: ```python 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`: ```python 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: ```python 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. ```html
``` `accounts/ntfy_test_result.html`: ```html {% if success %}