django-user-alerts 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. django_user_alerts-0.1.0/LICENSE +21 -0
  2. django_user_alerts-0.1.0/PKG-INFO +106 -0
  3. django_user_alerts-0.1.0/README.md +80 -0
  4. django_user_alerts-0.1.0/django_user_alerts.egg-info/PKG-INFO +106 -0
  5. django_user_alerts-0.1.0/django_user_alerts.egg-info/SOURCES.txt +23 -0
  6. django_user_alerts-0.1.0/django_user_alerts.egg-info/dependency_links.txt +1 -0
  7. django_user_alerts-0.1.0/django_user_alerts.egg-info/requires.txt +1 -0
  8. django_user_alerts-0.1.0/django_user_alerts.egg-info/top_level.txt +1 -0
  9. django_user_alerts-0.1.0/pyproject.toml +38 -0
  10. django_user_alerts-0.1.0/setup.cfg +4 -0
  11. django_user_alerts-0.1.0/tests/test_alerts.py +142 -0
  12. django_user_alerts-0.1.0/user_alerts/__init__.py +0 -0
  13. django_user_alerts-0.1.0/user_alerts/admin.py +37 -0
  14. django_user_alerts-0.1.0/user_alerts/apps.py +8 -0
  15. django_user_alerts-0.1.0/user_alerts/conf.py +20 -0
  16. django_user_alerts-0.1.0/user_alerts/migrations/0001_initial.py +54 -0
  17. django_user_alerts-0.1.0/user_alerts/migrations/__init__.py +0 -0
  18. django_user_alerts-0.1.0/user_alerts/models.py +91 -0
  19. django_user_alerts-0.1.0/user_alerts/static/user_alerts/dismiss.js +14 -0
  20. django_user_alerts-0.1.0/user_alerts/templates/user_alerts/alert.html +7 -0
  21. django_user_alerts-0.1.0/user_alerts/templates/user_alerts/alerts.html +6 -0
  22. django_user_alerts-0.1.0/user_alerts/templatetags/__init__.py +0 -0
  23. django_user_alerts-0.1.0/user_alerts/templatetags/user_alerts_tags.py +29 -0
  24. django_user_alerts-0.1.0/user_alerts/urls.py +9 -0
  25. django_user_alerts-0.1.0/user_alerts/views.py +26 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Carder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-user-alerts
3
+ Version: 0.1.0
4
+ Summary: Simple, admin-managed alerts shown to users of a Django site, as dismissible or permanent Bootstrap alerts.
5
+ Author-email: Michael Carder <michael.carder@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/mcldev/django-user-alerts
8
+ Project-URL: Source, https://github.com/mcldev/django-user-alerts
9
+ Project-URL: Issues, https://github.com/mcldev/django-user-alerts/issues
10
+ Keywords: django,alerts,notifications,announcements,bootstrap
11
+ Classifier: Environment :: Web Environment
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Django :: 4.2
14
+ Classifier: Framework :: Django :: 5.0
15
+ Classifier: Framework :: Django :: 5.1
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: >=3.12
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: django>=4.2
25
+ Dynamic: license-file
26
+
27
+ # django-user-alerts
28
+
29
+ Simple, admin-managed alerts for a Django site. Administrators post an alert (new service, outage, maintenance...) and
30
+ visitors see it as a Bootstrap 5 alert, either permanent or dismissible. No CMS, no jQuery, no other dependencies.
31
+
32
+ Requires Python 3.12+ and Django 4.2+.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install django-user-alerts
38
+ ```
39
+
40
+ ```python
41
+ # settings.py
42
+ INSTALLED_APPS = [..., "django.contrib.sessions", "user_alerts"]
43
+
44
+ # urls.py (only needed for the dismiss endpoint)
45
+ path("alerts/", include("user_alerts.urls")),
46
+ ```
47
+
48
+ ```bash
49
+ python manage.py migrate
50
+ ```
51
+
52
+ Add the request context processor (`django.template.context_processors.request`) if you don't already have it, then in
53
+ your base template:
54
+
55
+ ```django
56
+ {% load user_alerts_tags %}
57
+ {% render_user_alerts %}
58
+ ```
59
+
60
+ Manage alerts under **User alerts** in the Django admin.
61
+
62
+ ## Alert fields
63
+
64
+ | Field | Purpose |
65
+ |---|---|
66
+ | title / message | Bold title followed by the message |
67
+ | style | Bootstrap contextual class: info, success, warning, danger, ... |
68
+ | icon | Optional icon CSS classes (e.g. `bi bi-megaphone`, `fas fa-bullhorn`) |
69
+ | enabled, publish start/end | Show only inside the window |
70
+ | members only | Hide from anonymous visitors |
71
+ | dismissal | Cannot be dismissed, dismissed for the session, or dismissed permanently (signed-in users; anonymous visitors fall back to session) |
72
+ | order | Lower shows first |
73
+
74
+ ## Customising
75
+
76
+ Override templates by creating the same path in your project's `templates/` directory:
77
+
78
+ - `user_alerts/alerts.html` - the wrapper and dismiss script
79
+ - `user_alerts/alert.html` - one alert (context: `alert`, `allow_html`, `csrf_token`)
80
+
81
+ For full control use the data tag and write your own markup:
82
+
83
+ ```django
84
+ {% user_alerts as alerts %}
85
+ {% for alert in alerts %}...{% endfor %}
86
+ ```
87
+
88
+ The built-in markup uses Bootstrap 5's `btn-close`; the small `user_alerts/dismiss.js` tells the server when one is
89
+ closed, so make sure Bootstrap's JS is loaded for the close animation.
90
+
91
+ ## Settings
92
+
93
+ - `USER_ALERTS_STYLES` - list of `(value, label)` styles offered in the admin.
94
+ - `USER_ALERTS_ALLOW_HTML` - default `False` (messages are escaped, newlines kept). Set `True` to render the message as trusted HTML.
95
+
96
+ ## Development
97
+
98
+ ```bash
99
+ uv venv --python 3.12 && uv pip install django
100
+ DJANGO_SETTINGS_MODULE=tests.settings python -m django test tests
101
+ ```
102
+
103
+ ## Credit
104
+
105
+ Derived from the idea of [pinax-announcements](https://github.com/pinax/pinax-announcements) (MIT), rewritten as a
106
+ standalone app.
@@ -0,0 +1,80 @@
1
+ # django-user-alerts
2
+
3
+ Simple, admin-managed alerts for a Django site. Administrators post an alert (new service, outage, maintenance...) and
4
+ visitors see it as a Bootstrap 5 alert, either permanent or dismissible. No CMS, no jQuery, no other dependencies.
5
+
6
+ Requires Python 3.12+ and Django 4.2+.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install django-user-alerts
12
+ ```
13
+
14
+ ```python
15
+ # settings.py
16
+ INSTALLED_APPS = [..., "django.contrib.sessions", "user_alerts"]
17
+
18
+ # urls.py (only needed for the dismiss endpoint)
19
+ path("alerts/", include("user_alerts.urls")),
20
+ ```
21
+
22
+ ```bash
23
+ python manage.py migrate
24
+ ```
25
+
26
+ Add the request context processor (`django.template.context_processors.request`) if you don't already have it, then in
27
+ your base template:
28
+
29
+ ```django
30
+ {% load user_alerts_tags %}
31
+ {% render_user_alerts %}
32
+ ```
33
+
34
+ Manage alerts under **User alerts** in the Django admin.
35
+
36
+ ## Alert fields
37
+
38
+ | Field | Purpose |
39
+ |---|---|
40
+ | title / message | Bold title followed by the message |
41
+ | style | Bootstrap contextual class: info, success, warning, danger, ... |
42
+ | icon | Optional icon CSS classes (e.g. `bi bi-megaphone`, `fas fa-bullhorn`) |
43
+ | enabled, publish start/end | Show only inside the window |
44
+ | members only | Hide from anonymous visitors |
45
+ | dismissal | Cannot be dismissed, dismissed for the session, or dismissed permanently (signed-in users; anonymous visitors fall back to session) |
46
+ | order | Lower shows first |
47
+
48
+ ## Customising
49
+
50
+ Override templates by creating the same path in your project's `templates/` directory:
51
+
52
+ - `user_alerts/alerts.html` - the wrapper and dismiss script
53
+ - `user_alerts/alert.html` - one alert (context: `alert`, `allow_html`, `csrf_token`)
54
+
55
+ For full control use the data tag and write your own markup:
56
+
57
+ ```django
58
+ {% user_alerts as alerts %}
59
+ {% for alert in alerts %}...{% endfor %}
60
+ ```
61
+
62
+ The built-in markup uses Bootstrap 5's `btn-close`; the small `user_alerts/dismiss.js` tells the server when one is
63
+ closed, so make sure Bootstrap's JS is loaded for the close animation.
64
+
65
+ ## Settings
66
+
67
+ - `USER_ALERTS_STYLES` - list of `(value, label)` styles offered in the admin.
68
+ - `USER_ALERTS_ALLOW_HTML` - default `False` (messages are escaped, newlines kept). Set `True` to render the message as trusted HTML.
69
+
70
+ ## Development
71
+
72
+ ```bash
73
+ uv venv --python 3.12 && uv pip install django
74
+ DJANGO_SETTINGS_MODULE=tests.settings python -m django test tests
75
+ ```
76
+
77
+ ## Credit
78
+
79
+ Derived from the idea of [pinax-announcements](https://github.com/pinax/pinax-announcements) (MIT), rewritten as a
80
+ standalone app.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-user-alerts
3
+ Version: 0.1.0
4
+ Summary: Simple, admin-managed alerts shown to users of a Django site, as dismissible or permanent Bootstrap alerts.
5
+ Author-email: Michael Carder <michael.carder@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/mcldev/django-user-alerts
8
+ Project-URL: Source, https://github.com/mcldev/django-user-alerts
9
+ Project-URL: Issues, https://github.com/mcldev/django-user-alerts/issues
10
+ Keywords: django,alerts,notifications,announcements,bootstrap
11
+ Classifier: Environment :: Web Environment
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Django :: 4.2
14
+ Classifier: Framework :: Django :: 5.0
15
+ Classifier: Framework :: Django :: 5.1
16
+ Classifier: Framework :: Django :: 5.2
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: >=3.12
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: django>=4.2
25
+ Dynamic: license-file
26
+
27
+ # django-user-alerts
28
+
29
+ Simple, admin-managed alerts for a Django site. Administrators post an alert (new service, outage, maintenance...) and
30
+ visitors see it as a Bootstrap 5 alert, either permanent or dismissible. No CMS, no jQuery, no other dependencies.
31
+
32
+ Requires Python 3.12+ and Django 4.2+.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install django-user-alerts
38
+ ```
39
+
40
+ ```python
41
+ # settings.py
42
+ INSTALLED_APPS = [..., "django.contrib.sessions", "user_alerts"]
43
+
44
+ # urls.py (only needed for the dismiss endpoint)
45
+ path("alerts/", include("user_alerts.urls")),
46
+ ```
47
+
48
+ ```bash
49
+ python manage.py migrate
50
+ ```
51
+
52
+ Add the request context processor (`django.template.context_processors.request`) if you don't already have it, then in
53
+ your base template:
54
+
55
+ ```django
56
+ {% load user_alerts_tags %}
57
+ {% render_user_alerts %}
58
+ ```
59
+
60
+ Manage alerts under **User alerts** in the Django admin.
61
+
62
+ ## Alert fields
63
+
64
+ | Field | Purpose |
65
+ |---|---|
66
+ | title / message | Bold title followed by the message |
67
+ | style | Bootstrap contextual class: info, success, warning, danger, ... |
68
+ | icon | Optional icon CSS classes (e.g. `bi bi-megaphone`, `fas fa-bullhorn`) |
69
+ | enabled, publish start/end | Show only inside the window |
70
+ | members only | Hide from anonymous visitors |
71
+ | dismissal | Cannot be dismissed, dismissed for the session, or dismissed permanently (signed-in users; anonymous visitors fall back to session) |
72
+ | order | Lower shows first |
73
+
74
+ ## Customising
75
+
76
+ Override templates by creating the same path in your project's `templates/` directory:
77
+
78
+ - `user_alerts/alerts.html` - the wrapper and dismiss script
79
+ - `user_alerts/alert.html` - one alert (context: `alert`, `allow_html`, `csrf_token`)
80
+
81
+ For full control use the data tag and write your own markup:
82
+
83
+ ```django
84
+ {% user_alerts as alerts %}
85
+ {% for alert in alerts %}...{% endfor %}
86
+ ```
87
+
88
+ The built-in markup uses Bootstrap 5's `btn-close`; the small `user_alerts/dismiss.js` tells the server when one is
89
+ closed, so make sure Bootstrap's JS is loaded for the close animation.
90
+
91
+ ## Settings
92
+
93
+ - `USER_ALERTS_STYLES` - list of `(value, label)` styles offered in the admin.
94
+ - `USER_ALERTS_ALLOW_HTML` - default `False` (messages are escaped, newlines kept). Set `True` to render the message as trusted HTML.
95
+
96
+ ## Development
97
+
98
+ ```bash
99
+ uv venv --python 3.12 && uv pip install django
100
+ DJANGO_SETTINGS_MODULE=tests.settings python -m django test tests
101
+ ```
102
+
103
+ ## Credit
104
+
105
+ Derived from the idea of [pinax-announcements](https://github.com/pinax/pinax-announcements) (MIT), rewritten as a
106
+ standalone app.
@@ -0,0 +1,23 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ django_user_alerts.egg-info/PKG-INFO
5
+ django_user_alerts.egg-info/SOURCES.txt
6
+ django_user_alerts.egg-info/dependency_links.txt
7
+ django_user_alerts.egg-info/requires.txt
8
+ django_user_alerts.egg-info/top_level.txt
9
+ tests/test_alerts.py
10
+ user_alerts/__init__.py
11
+ user_alerts/admin.py
12
+ user_alerts/apps.py
13
+ user_alerts/conf.py
14
+ user_alerts/models.py
15
+ user_alerts/urls.py
16
+ user_alerts/views.py
17
+ user_alerts/migrations/0001_initial.py
18
+ user_alerts/migrations/__init__.py
19
+ user_alerts/static/user_alerts/dismiss.js
20
+ user_alerts/templates/user_alerts/alert.html
21
+ user_alerts/templates/user_alerts/alerts.html
22
+ user_alerts/templatetags/__init__.py
23
+ user_alerts/templatetags/user_alerts_tags.py
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "django-user-alerts"
7
+ version = "0.1.0"
8
+ description = "Simple, admin-managed alerts shown to users of a Django site, as dismissible or permanent Bootstrap alerts."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Michael Carder", email = "michael.carder@gmail.com" }]
13
+ keywords = ["django", "alerts", "notifications", "announcements", "bootstrap"]
14
+ requires-python = ">=3.12"
15
+ dependencies = ["django>=4.2"]
16
+ classifiers = [
17
+ "Environment :: Web Environment",
18
+ "Framework :: Django",
19
+ "Framework :: Django :: 4.2",
20
+ "Framework :: Django :: 5.0",
21
+ "Framework :: Django :: 5.1",
22
+ "Framework :: Django :: 5.2",
23
+ "Intended Audience :: Developers",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/mcldev/django-user-alerts"
31
+ Source = "https://github.com/mcldev/django-user-alerts"
32
+ Issues = "https://github.com/mcldev/django-user-alerts/issues"
33
+
34
+ [tool.setuptools.packages.find]
35
+ include = ["user_alerts*"]
36
+
37
+ [tool.setuptools.package-data]
38
+ user_alerts = ["templates/**/*", "static/**/*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,142 @@
1
+ from datetime import timedelta
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.template import Context, Template
5
+ from unittest.mock import patch
6
+
7
+ from django.test import RequestFactory, TestCase
8
+ from django.utils import timezone
9
+
10
+ from user_alerts import conf
11
+ from user_alerts.models import Alert, Dismissal
12
+
13
+ User = get_user_model()
14
+
15
+
16
+ def make_alert(**kwargs):
17
+ kwargs.setdefault("title", "Maintenance")
18
+ return Alert.objects.create(**kwargs)
19
+
20
+
21
+ class ActiveWindowTests(TestCase):
22
+ def test_active_respects_enabled_and_window(self):
23
+ now = timezone.now()
24
+ live = make_alert(title="live")
25
+ make_alert(title="disabled", enabled=False)
26
+ make_alert(title="future", publish_start=now + timedelta(hours=1))
27
+ make_alert(title="expired", publish_end=now - timedelta(hours=1))
28
+ self.assertEqual(list(Alert.objects.active()), [live])
29
+ self.assertTrue(live.is_active)
30
+
31
+ def test_ordering(self):
32
+ b = make_alert(title="b", order=2)
33
+ a = make_alert(title="a", order=1)
34
+ self.assertEqual(list(Alert.objects.all()), [a, b])
35
+
36
+
37
+ class VisibilityTests(TestCase):
38
+ def request_for(self, user=None):
39
+ request = RequestFactory().get("/")
40
+ request.session = self.client.session
41
+ request.user = user or type("Anon", (), {"is_authenticated": False})()
42
+ return request
43
+
44
+ def test_members_only_hidden_from_anonymous(self):
45
+ make_alert(title="public")
46
+ make_alert(title="private", members_only=True)
47
+ titles = [a.title for a in Alert.objects.for_request(self.request_for())]
48
+ self.assertEqual(titles, ["public"])
49
+
50
+ def test_members_only_shown_to_users(self):
51
+ user = User.objects.create_user("u")
52
+ make_alert(title="private", members_only=True)
53
+ self.assertEqual(Alert.objects.for_request(self.request_for(user)).count(), 1)
54
+
55
+ def test_permanent_dismissal_hides_for_that_user_only(self):
56
+ u1, u2 = User.objects.create_user("u1"), User.objects.create_user("u2")
57
+ alert = make_alert(dismissal_type=Alert.DISMISS_PERMANENT)
58
+ Dismissal.objects.create(user=u1, alert=alert)
59
+ self.assertEqual(Alert.objects.for_request(self.request_for(u1)).count(), 0)
60
+ self.assertEqual(Alert.objects.for_request(self.request_for(u2)).count(), 1)
61
+
62
+
63
+ class DismissViewTests(TestCase):
64
+ def url(self, alert):
65
+ return alert.dismiss_url()
66
+
67
+ def test_no_dismiss_url_when_not_dismissible(self):
68
+ self.assertIsNone(make_alert(dismissal_type=Alert.DISMISS_NONE).dismiss_url())
69
+
70
+ def test_get_not_allowed(self):
71
+ alert = make_alert()
72
+ self.assertEqual(self.client.get(self.url(alert)).status_code, 405)
73
+
74
+ def test_non_dismissible_returns_409(self):
75
+ alert = make_alert(dismissal_type=Alert.DISMISS_NONE)
76
+ url = f"/alerts/{alert.pk}/dismiss/"
77
+ self.assertEqual(self.client.post(url).status_code, 409)
78
+
79
+ def test_session_dismissal_hides_alert(self):
80
+ alert = make_alert()
81
+ self.assertEqual(self.client.post(self.url(alert)).status_code, 204)
82
+ response = self.client.get("/alerts/") # no such page; just keep session
83
+ request = RequestFactory().get("/")
84
+ request.session = self.client.session
85
+ request.user = type("Anon", (), {"is_authenticated": False})()
86
+ self.assertEqual(Alert.objects.for_request(request).count(), 0)
87
+
88
+ def test_permanent_dismissal_recorded_once(self):
89
+ user = User.objects.create_user("u")
90
+ alert = make_alert(dismissal_type=Alert.DISMISS_PERMANENT)
91
+ self.client.force_login(user)
92
+ self.client.post(self.url(alert))
93
+ self.client.post(self.url(alert))
94
+ self.assertEqual(Dismissal.objects.filter(user=user, alert=alert).count(), 1)
95
+
96
+ def test_permanent_falls_back_to_session_for_anonymous(self):
97
+ alert = make_alert(dismissal_type=Alert.DISMISS_PERMANENT)
98
+ self.assertEqual(self.client.post(self.url(alert)).status_code, 204)
99
+ self.assertEqual(Dismissal.objects.count(), 0)
100
+ self.assertIn(alert.pk, self.client.session["user_alerts_dismissed"])
101
+
102
+ def test_inactive_alert_404(self):
103
+ alert = make_alert(enabled=False)
104
+ self.assertEqual(self.client.post(self.url(alert)).status_code, 404)
105
+
106
+
107
+ class TemplateTagTests(TestCase):
108
+ def render(self, source, user=None):
109
+ request = RequestFactory().get("/")
110
+ request.session = self.client.session
111
+ request.user = user or type("Anon", (), {"is_authenticated": False})()
112
+ return Template("{% load user_alerts_tags %}" + source).render(Context({"request": request}))
113
+
114
+ def test_render_tag_outputs_bootstrap_alert(self):
115
+ make_alert(title="Down", message="Back soon", style="danger", icon="fas fa-bullhorn")
116
+ html = self.render("{% render_user_alerts %}")
117
+ self.assertIn("alert alert-danger alert-dismissible", html)
118
+ self.assertIn("Down", html)
119
+ self.assertIn("fas fa-bullhorn", html)
120
+ self.assertIn("dismiss.js", html)
121
+
122
+ def test_non_dismissible_has_no_close_button(self):
123
+ make_alert(dismissal_type=Alert.DISMISS_NONE)
124
+ html = self.render("{% render_user_alerts %}")
125
+ self.assertNotIn("btn-close", html)
126
+
127
+ def test_nothing_rendered_without_alerts(self):
128
+ self.assertEqual(self.render("{% render_user_alerts %}").strip(), "")
129
+
130
+ def test_message_escaped_by_default(self):
131
+ make_alert(message="<script>x</script>")
132
+ self.assertNotIn("<script>x", self.render("{% render_user_alerts %}"))
133
+
134
+ def test_allow_html_setting(self):
135
+ make_alert(message="<b>bold</b>")
136
+ with patch.object(conf, "ALLOW_HTML", True):
137
+ self.assertIn("<b>bold</b>", self.render("{% render_user_alerts %}"))
138
+
139
+ def test_user_alerts_tag_as_variable(self):
140
+ make_alert(title="one")
141
+ out = self.render("{% user_alerts as a %}{{ a|length }}")
142
+ self.assertEqual(out, "1")
File without changes
@@ -0,0 +1,37 @@
1
+ from django import forms
2
+ from django.contrib import admin
3
+
4
+ from . import conf
5
+ from .models import Alert, Dismissal
6
+
7
+
8
+ class AlertAdminForm(forms.ModelForm):
9
+ style = forms.ChoiceField(choices=conf.STYLES, required=False)
10
+
11
+ class Meta:
12
+ model = Alert
13
+ fields = "__all__"
14
+
15
+
16
+ @admin.register(Alert)
17
+ class AlertAdmin(admin.ModelAdmin):
18
+ form = AlertAdminForm
19
+ list_display = ("title", "style", "enabled", "is_active", "members_only", "dismissal_type", "order")
20
+ list_editable = ("enabled", "order")
21
+ list_filter = ("enabled", "members_only", "style")
22
+ search_fields = ("title", "message")
23
+
24
+ @admin.display(boolean=True, description="Live now")
25
+ def is_active(self, obj):
26
+ return obj.is_active
27
+
28
+ def save_model(self, request, obj, form, change):
29
+ if not change:
30
+ obj.created_by = request.user
31
+ super().save_model(request, obj, form, change)
32
+
33
+
34
+ @admin.register(Dismissal)
35
+ class DismissalAdmin(admin.ModelAdmin):
36
+ list_display = ("user", "alert", "dismissed_at")
37
+ raw_id_fields = ("user",)
@@ -0,0 +1,8 @@
1
+ from django.apps import AppConfig
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+
5
+ class UserAlertsConfig(AppConfig):
6
+ name = "user_alerts"
7
+ verbose_name = _("User alerts")
8
+ default_auto_field = "django.db.models.AutoField"
@@ -0,0 +1,20 @@
1
+ from django.conf import settings
2
+
3
+ DEFAULT_STYLES = [
4
+ ("info", "Info"),
5
+ ("success", "Success"),
6
+ ("warning", "Warning"),
7
+ ("danger", "Danger"),
8
+ ("primary", "Primary"),
9
+ ("secondary", "Secondary"),
10
+ ]
11
+
12
+ # Bootstrap contextual alert styles offered in the admin. Override with e.g.
13
+ # USER_ALERTS_STYLES = [("info", "Info"), ("danger", "Outage")]
14
+ STYLES = getattr(settings, "USER_ALERTS_STYLES", DEFAULT_STYLES)
15
+
16
+ # Alert text is escaped by default. Set True to render the admin-entered
17
+ # message as trusted HTML.
18
+ ALLOW_HTML = getattr(settings, "USER_ALERTS_ALLOW_HTML", False)
19
+
20
+ SESSION_KEY = "user_alerts_dismissed"
@@ -0,0 +1,54 @@
1
+ # Generated by Django 4.2.30 on 2026-11-07 08:13
2
+
3
+ from django.conf import settings
4
+ from django.db import migrations, models
5
+ import django.db.models.deletion
6
+ import django.utils.timezone
7
+
8
+
9
+ class Migration(migrations.Migration):
10
+
11
+ initial = True
12
+
13
+ dependencies = [
14
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
15
+ ]
16
+
17
+ operations = [
18
+ migrations.CreateModel(
19
+ name='Alert',
20
+ fields=[
21
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
22
+ ('title', models.CharField(max_length=100, verbose_name='title')),
23
+ ('message', models.TextField(blank=True, verbose_name='message')),
24
+ ('style', models.CharField(blank=True, default='info', max_length=20, verbose_name='style')),
25
+ ('icon', models.CharField(blank=True, help_text="Optional icon CSS classes, e.g. 'bi bi-exclamation-triangle' or 'fas fa-bullhorn'.", max_length=100, verbose_name='icon')),
26
+ ('enabled', models.BooleanField(default=True, verbose_name='enabled')),
27
+ ('members_only', models.BooleanField(default=False, verbose_name='signed-in users only')),
28
+ ('dismissal_type', models.IntegerField(choices=[(1, 'Cannot be dismissed'), (2, 'Dismissed until the session ends'), (3, 'Dismissed permanently (signed-in users)')], default=2, verbose_name='dismissal')),
29
+ ('publish_start', models.DateTimeField(default=django.utils.timezone.now, verbose_name='publish start')),
30
+ ('publish_end', models.DateTimeField(blank=True, null=True, verbose_name='publish end')),
31
+ ('order', models.PositiveIntegerField(default=0, help_text='Lower numbers show first.', verbose_name='order')),
32
+ ('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
33
+ ('created_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL, verbose_name='created by')),
34
+ ],
35
+ options={
36
+ 'verbose_name': 'alert',
37
+ 'verbose_name_plural': 'alerts',
38
+ 'ordering': ['order', '-created'],
39
+ },
40
+ ),
41
+ migrations.CreateModel(
42
+ name='Dismissal',
43
+ fields=[
44
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
45
+ ('dismissed_at', models.DateTimeField(default=django.utils.timezone.now)),
46
+ ('alert', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='dismissals', to='user_alerts.alert')),
47
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='alert_dismissals', to=settings.AUTH_USER_MODEL)),
48
+ ],
49
+ ),
50
+ migrations.AddConstraint(
51
+ model_name='dismissal',
52
+ constraint=models.UniqueConstraint(fields=('user', 'alert'), name='user_alerts_unique_dismissal'),
53
+ ),
54
+ ]
@@ -0,0 +1,91 @@
1
+ from django.conf import settings
2
+ from django.db import models
3
+ from django.db.models import Q
4
+ from django.urls import reverse
5
+ from django.utils import timezone
6
+ from django.utils.translation import gettext_lazy as _
7
+
8
+ from . import conf
9
+
10
+
11
+ class AlertQuerySet(models.QuerySet):
12
+ def active(self, now=None):
13
+ """Enabled alerts whose publish window includes ``now``."""
14
+ now = now or timezone.now()
15
+ return self.filter(enabled=True, publish_start__lte=now).filter(
16
+ Q(publish_end__isnull=True) | Q(publish_end__gt=now)
17
+ )
18
+
19
+ def for_request(self, request):
20
+ """Active alerts this request's user should currently see."""
21
+ qs = self.active()
22
+ user = getattr(request, "user", None)
23
+ if user is not None and user.is_authenticated:
24
+ qs = qs.exclude(dismissals__user=user)
25
+ else:
26
+ qs = qs.filter(members_only=False)
27
+ session = getattr(request, "session", None)
28
+ dismissed = session.get(conf.SESSION_KEY, []) if session is not None else []
29
+ return qs.exclude(pk__in=dismissed)
30
+
31
+
32
+ class Alert(models.Model):
33
+ DISMISS_NONE = 1
34
+ DISMISS_SESSION = 2
35
+ DISMISS_PERMANENT = 3
36
+ DISMISSAL_CHOICES = [
37
+ (DISMISS_NONE, _("Cannot be dismissed")),
38
+ (DISMISS_SESSION, _("Dismissed until the session ends")),
39
+ (DISMISS_PERMANENT, _("Dismissed permanently (signed-in users)")),
40
+ ]
41
+
42
+ title = models.CharField(_("title"), max_length=100)
43
+ message = models.TextField(_("message"), blank=True)
44
+ style = models.CharField(_("style"), max_length=20, default="info", blank=True)
45
+ icon = models.CharField(
46
+ _("icon"), max_length=100, blank=True,
47
+ help_text=_("Optional icon CSS classes, e.g. 'bi bi-exclamation-triangle' or 'fas fa-bullhorn'."),
48
+ )
49
+ enabled = models.BooleanField(_("enabled"), default=True)
50
+ members_only = models.BooleanField(_("signed-in users only"), default=False)
51
+ dismissal_type = models.IntegerField(_("dismissal"), choices=DISMISSAL_CHOICES, default=DISMISS_SESSION)
52
+ publish_start = models.DateTimeField(_("publish start"), default=timezone.now)
53
+ publish_end = models.DateTimeField(_("publish end"), blank=True, null=True)
54
+ order = models.PositiveIntegerField(_("order"), default=0, help_text=_("Lower numbers show first."))
55
+ created = models.DateTimeField(_("created"), auto_now_add=True)
56
+ created_by = models.ForeignKey(
57
+ settings.AUTH_USER_MODEL, verbose_name=_("created by"),
58
+ null=True, blank=True, editable=False, on_delete=models.SET_NULL, related_name="+",
59
+ )
60
+
61
+ objects = AlertQuerySet.as_manager()
62
+
63
+ class Meta:
64
+ verbose_name = _("alert")
65
+ verbose_name_plural = _("alerts")
66
+ ordering = ["order", "-created"]
67
+
68
+ def __str__(self):
69
+ return self.title
70
+
71
+ @property
72
+ def is_active(self):
73
+ now = timezone.now()
74
+ return self.enabled and self.publish_start <= now and (self.publish_end is None or self.publish_end > now)
75
+
76
+ @property
77
+ def dismissible(self):
78
+ return self.dismissal_type != self.DISMISS_NONE
79
+
80
+ def dismiss_url(self):
81
+ if self.dismissible:
82
+ return reverse("user_alerts:dismiss", args=[self.pk])
83
+
84
+
85
+ class Dismissal(models.Model):
86
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="alert_dismissals")
87
+ alert = models.ForeignKey(Alert, on_delete=models.CASCADE, related_name="dismissals")
88
+ dismissed_at = models.DateTimeField(default=timezone.now)
89
+
90
+ class Meta:
91
+ constraints = [models.UniqueConstraint(fields=["user", "alert"], name="user_alerts_unique_dismissal")]
@@ -0,0 +1,14 @@
1
+ // Tell the server when a visitor closes a dismissible alert. Needs Bootstrap 5
2
+ // (for the close button); no jQuery.
3
+ document.addEventListener("click", function (event) {
4
+ var button = event.target.closest(".user-alert .btn-close");
5
+ if (!button) return;
6
+ var alert = button.closest(".user-alert");
7
+ var url = alert && alert.dataset.dismissUrl;
8
+ if (!url) return;
9
+ fetch(url, {
10
+ method: "POST",
11
+ credentials: "same-origin",
12
+ headers: { "X-CSRFToken": alert.dataset.csrfToken || "" },
13
+ }).catch(function (error) { console.warn("Alert dismissal not saved:", error); });
14
+ });
@@ -0,0 +1,7 @@
1
+ <div class="user-alert alert alert-{{ alert.style|default:'info' }}{% if alert.dismiss_url %} alert-dismissible fade show{% endif %}"
2
+ role="alert"{% if alert.dismiss_url %} data-dismiss-url="{{ alert.dismiss_url }}" data-csrf-token="{{ csrf_token }}"{% endif %}>
3
+ {% if alert.icon %}<i class="{{ alert.icon }} me-2" aria-hidden="true"></i>{% endif %}
4
+ <strong>{{ alert.title }}</strong>{% if alert.message %}
5
+ {% if allow_html %}{{ alert.message|safe }}{% else %}{{ alert.message|linebreaksbr }}{% endif %}{% endif %}
6
+ {% if alert.dismiss_url %}<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>{% endif %}
7
+ </div>
@@ -0,0 +1,6 @@
1
+ {% load static %}{% if alerts %}
2
+ <div class="user-alerts">
3
+ {% for alert in alerts %}{% include "user_alerts/alert.html" %}{% endfor %}
4
+ </div>
5
+ <script src="{% static 'user_alerts/dismiss.js' %}" defer></script>
6
+ {% endif %}
@@ -0,0 +1,29 @@
1
+ from django import template
2
+
3
+ from user_alerts import conf
4
+ from user_alerts.models import Alert
5
+
6
+ register = template.Library()
7
+
8
+
9
+ @register.simple_tag(takes_context=True)
10
+ def user_alerts(context):
11
+ """``{% user_alerts as alerts %}`` - alerts the current visitor should see."""
12
+ request = context.get("request")
13
+ if request is None:
14
+ return Alert.objects.none()
15
+ return Alert.objects.for_request(request)
16
+
17
+
18
+ @register.inclusion_tag("user_alerts/alerts.html", takes_context=True)
19
+ def render_user_alerts(context):
20
+ """``{% render_user_alerts %}`` - render all current alerts.
21
+
22
+ Override ``user_alerts/alerts.html`` (or ``user_alerts/alert.html``) in your
23
+ project's templates to change the markup.
24
+ """
25
+ return {
26
+ "alerts": user_alerts(context),
27
+ "allow_html": conf.ALLOW_HTML,
28
+ "csrf_token": context.get("csrf_token", ""),
29
+ }
@@ -0,0 +1,9 @@
1
+ from django.urls import path
2
+
3
+ from .views import DismissView
4
+
5
+ app_name = "user_alerts"
6
+
7
+ urlpatterns = [
8
+ path("<int:pk>/dismiss/", DismissView.as_view(), name="dismiss"),
9
+ ]
@@ -0,0 +1,26 @@
1
+ from django.http import HttpResponse
2
+ from django.shortcuts import get_object_or_404
3
+ from django.views import View
4
+
5
+ from . import conf
6
+ from .models import Alert, Dismissal
7
+
8
+
9
+ class DismissView(View):
10
+ """POST-only: record that the current visitor has dismissed an alert."""
11
+
12
+ http_method_names = ["post"]
13
+
14
+ def post(self, request, pk):
15
+ alert = get_object_or_404(Alert.objects.active(), pk=pk)
16
+ if not alert.dismissible:
17
+ return HttpResponse(status=409)
18
+ user = request.user
19
+ if alert.dismissal_type == Alert.DISMISS_PERMANENT and user.is_authenticated:
20
+ Dismissal.objects.get_or_create(user=user, alert=alert)
21
+ else:
22
+ # Session dismissal; also the fallback for anonymous visitors.
23
+ dismissed = set(request.session.get(conf.SESSION_KEY, []))
24
+ dismissed.add(alert.pk)
25
+ request.session[conf.SESSION_KEY] = sorted(dismissed)
26
+ return HttpResponse(status=204)