diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0696e07 --- /dev/null +++ b/.gitignore @@ -0,0 +1,83 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# Cython debug symbols +cython_debug/ + +# Distribution / packaging +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Sentry +.sentryclirc + +# Staticfiles +staticfiles/ +static/ +media/ + +# Jupyter Notebook +.ipynb_checkpoints + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# PyCharm +.idea/ + +# VSCode +.vscode/ diff --git a/README.md b/README.md index 97faad1..e836272 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,6 @@ Currently, it Supports Sending Push Notification to **Firefox 46+, Chrome 52+ an ---------- - Installation and Setup ---------------------- @@ -27,13 +26,15 @@ INSTALLED_APPS = ( ``` If you would like to send notification to Google Chrome Users, you need to add a ``WEBPUSH_SETTINGS`` entry with the **Vapid Credentials** Like following: + ```python WEBPUSH_SETTINGS = { "VAPID_PUBLIC_KEY": "Vapid Public Key", - "VAPID_PRIVATE_KEY":"Vapid Private Key", + "VAPID_PRIVATE_KEY": "Vapid Private Key", "VAPID_ADMIN_EMAIL": "admin@example.com" } ``` + **Replace ``"Vapid Public Key"`` and ``"Vapid Private Key"`` with your Vapid Keys. Also replace ``admin@example.com`` with your email so that the push server of browser can reach to you if anything goes wrong.** > **To know how to obtain Vapid Keys please see this [`py_vapid`](https://github.com/web-push-libs/vapid/tree/master/python) and [Google Developer Documentation](https://developers.google.com/web/fundamentals/push-notifications/subscribing-a-user#how_to_create_application_server_keys). You can obtain one easily from [web-push-codelab.glitch.me](https://web-push-codelab.glitch.me/). ``Application Server Keys`` and ``Vapid Keys`` both are same.** @@ -41,11 +42,20 @@ WEBPUSH_SETTINGS = { Then include `webpush` in the `urls.py` ```python +# Django >= 2.0 +from django.urls import path, include + urlpatterns = [ - url(r'^webpush/', include('webpush.urls')) + path('webpush/', include('webpush.urls')) ] - ``` +# Django < 2.0 +from django.conf.urls import url, include + +urlpatterns = [ + url(r'^webpush/', include('webpush.urls')) +] +``` `django-webpush` is shipped with built in **`jinja`** support. If you would like to use with jinja backend, @@ -67,15 +77,13 @@ TEMPLATES = [ ] ``` - **Then run Migration by ***`python manage.py migrate`***** - - Adding Web Push Information in Template --------------------------------------- So in template, you need to load `webpush_notifications` custom template tag by following: + - If you are using built in templating engine, add `{% load webpush_notifications %}` in the template - If you are using **jinja** templating engine, you do not need to load anything. @@ -85,17 +93,21 @@ Next, inside the `` tag add `webpush_header` according to your temp # For django templating engine {% webpush_header %} + # For jinja templating engine {{ webpush_header() }} ``` + Next, inside the `` tag, insert `webush_button` where you would like to see the **Subscribe to Push Messaging** Button. Like following ```html

Hello World!

+ # For django templating engine {% webpush_button %} + # For jinja templating engine {{ webpush_button() }} @@ -106,8 +118,10 @@ Or if you want to add custom classes (e.g. bootstrap) ```html

Hello World!

+ # For django templating engine {% webpush_button with_class="btn btn-outline-info" %} + # For jinja templating engine {{ webpush_button(with_class="btn btn-outline-info") }} @@ -122,6 +136,7 @@ Or if you want to add custom classes (e.g. bootstrap) return render(request, 'template.html', {"webpush":webpush}) ``` + > **Note:** If you dont pass `group` through the `webpush` context, only logged in users can see the button for subscription and able to get notification. ---------- @@ -134,7 +149,6 @@ So in order to send notification, see below. - If you would like to send notification to a specific group, do like following: - ```python from webpush import send_group_notification @@ -148,6 +162,7 @@ So in order to send notification, see below. ``` - If you would like to send Notification to a specific user, do like following + ```python from webpush import send_user_notification @@ -174,14 +189,14 @@ So in order to send notification, see below. send_group_notification(group_name="my_group", payload=payload, ttl=1000) ``` + **And the subscribers will get a notification like:** ![Web Push Notification icon](http://i.imgur.com/Vr1RMvF.png) **That will open https://www.example.com if clicked.** - -- If you want fine grained control over sending a single push message, do like following +- If you want fine grained control over sending a single push message, do like following ```python from webpush.utils import send_to_subscription @@ -194,18 +209,36 @@ So in order to send notification, see below. send_to_subscription(push_info.subscription, payload) ``` - - - - **And the subscribers will get a notification like** ![Web Push Notification](http://i.imgur.com/VA6cxRc.png) +Contributing +------------ + +If you would like to contribute, fork the repository and send a pull request. You can also open an issue if you find any bug or want to suggest a feature. + +Internationalization +--------------------- + +The package is shipped with built in internationalization support. + +If you would like to add more language or update translation, you can run the following command: + +```bash + +# Add js translation +django-admin makemessages -d djangojs -l + +# Add python translation +django-admin makemessages -l +``` + +After that, you can run `django-admin compilemessages` to compile the messages. License ======= ----- + Copyright © 2018 Safwan Rahman This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. diff --git a/webpush/__init__.py b/webpush/__init__.py index 55bed93..b89650a 100644 --- a/webpush/__init__.py +++ b/webpush/__init__.py @@ -2,10 +2,12 @@ from .utils import send_notification_to_group, send_notification_to_user + def send_group_notification(group_name, payload, ttl=0, exclude_user_id=None): payload = json.dumps(payload) send_notification_to_group(group_name, payload, ttl, exclude_user_id) + def send_user_notification(user, payload, ttl=0): payload = json.dumps(payload) send_notification_to_user(user, payload, ttl) diff --git a/webpush/admin.py b/webpush/admin.py index 29d7682..2683059 100644 --- a/webpush/admin.py +++ b/webpush/admin.py @@ -1,6 +1,7 @@ import json from django.contrib import admin +from django.utils.translation import gettext_lazy as _ from .models import PushInformation from .utils import _send_notification @@ -8,16 +9,18 @@ class PushInfoAdmin(admin.ModelAdmin): list_display = ("__str__", "user", "subscription", "group") + actions = ("send_test_message",) def send_test_message(self, request, queryset): - payload = {"head": "Hey", "body": "Hello World"} + payload = {"head": _("Hey"), "body": _("Hello World")} for device in queryset: notification = _send_notification(device.subscription, json.dumps(payload), 0) if notification: - self.message_user(request, "Test sent successfully") + self.message_user(request, _("Test sent successfully")) else: - self.message_user(request, "Deprecated subscription deleted") + self.message_user(request, _("Deprecated subscription deleted")) + send_test_message.short_description = _("Send test message") admin.site.register(PushInformation, PushInfoAdmin) diff --git a/webpush/forms.py b/webpush/forms.py index ab8ab28..c86281c 100644 --- a/webpush/forms.py +++ b/webpush/forms.py @@ -1,14 +1,15 @@ from django import forms +from django.utils.translation import gettext_lazy as _ from .models import Group, PushInformation, SubscriptionInfo class WebPushForm(forms.Form): - group = forms.CharField(max_length=255, required=False) + group = forms.CharField(max_length=255, required=False, label=_("Group")) status_type = forms.ChoiceField(choices=[ - ('subscribe', 'subscribe'), - ('unsubscribe', 'unsubscribe') - ]) + ('subscribe', _('Subscribe')), + ('unsubscribe', _('Unsubscribe')) + ], label=_("Status Type")) def save_or_delete(self, subscription, user, status_type, group_name): # Ensure get_or_create matches exactly @@ -18,15 +19,15 @@ def save_or_delete(self, subscription, user, status_type, group_name): data["user"] = user if group_name: - group, created = Group.objects.get_or_create(name=group_name) + group, _ = Group.objects.get_or_create(name=group_name) data["group"] = group data["subscription"] = subscription - push_info, created = PushInformation.objects.get_or_create(**data) + push_info, _ = PushInformation.objects.get_or_create(**data) # If unsubscribe is called, that means need to delete the browser - # and notification info from server. + # and notification info from server. if status_type == "unsubscribe": push_info.delete() subscription.delete() @@ -39,5 +40,5 @@ class Meta: fields = ('endpoint', 'auth', 'p256dh', 'browser', 'user_agent') def get_or_save(self): - subscription, created = SubscriptionInfo.objects.get_or_create(**self.cleaned_data) + subscription, _ = SubscriptionInfo.objects.get_or_create(**self.cleaned_data) return subscription diff --git a/webpush/locale/en/LC_MESSAGES/django.mo b/webpush/locale/en/LC_MESSAGES/django.mo new file mode 100644 index 0000000..71cbdf3 Binary files /dev/null and b/webpush/locale/en/LC_MESSAGES/django.mo differ diff --git a/webpush/locale/en/LC_MESSAGES/django.po b/webpush/locale/en/LC_MESSAGES/django.po new file mode 100644 index 0000000..4f21577 --- /dev/null +++ b/webpush/locale/en/LC_MESSAGES/django.po @@ -0,0 +1,107 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-09-02 17:03-0300\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: admin.py:16 +msgid "Hey" +msgstr "" + +#: admin.py:16 +msgid "Hello World" +msgstr "" + +#: admin.py:20 +msgid "Test sent successfully" +msgstr "" + +#: admin.py:22 +msgid "Deprecated subscription deleted" +msgstr "" + +#: admin.py:23 +msgid "Send test message" +msgstr "" + +#: forms.py:8 models.py:14 models.py:38 +msgid "Group" +msgstr "" + +#: forms.py:10 +msgid "Subscribe" +msgstr "" + +#: forms.py:11 +msgid "Unsubscribe" +msgstr "" + +#: forms.py:12 +msgid "Status Type" +msgstr "" + +#: models.py:8 +msgid "Name" +msgstr "" + +#: models.py:15 +msgid "Groups" +msgstr "" + +#: models.py:20 +msgid "Browser" +msgstr "" + +#: models.py:21 +msgid "User Agent" +msgstr "" + +#: models.py:22 +msgid "Endpoint" +msgstr "" + +#: models.py:23 +msgid "Auth" +msgstr "" + +#: models.py:24 +msgid "P256DH" +msgstr "" + +#: models.py:30 +msgid "Subscription Info" +msgstr "" + +#: models.py:31 +msgid "Subscription Infos" +msgstr "" + +#: models.py:36 +msgid "User" +msgstr "" + +#: models.py:37 +msgid "Subscription" +msgstr "" + +#: models.py:47 +msgid "At least user or group should be present" +msgstr "" + +#: models.py:56 models.py:57 +msgid "Push Information" +msgstr "" diff --git a/webpush/locale/en/LC_MESSAGES/djangojs.po b/webpush/locale/en/LC_MESSAGES/djangojs.po index c2b1c1d..5f8d5c9 100644 --- a/webpush/locale/en/LC_MESSAGES/djangojs.po +++ b/webpush/locale/en/LC_MESSAGES/djangojs.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2020-11-25 10:06-0500\n" +"POT-Creation-Date: 2024-09-02 17:03-0300\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,47 +18,47 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" -#: static/webpush/webpush.js:31 -msgid "Service workers are not supported in your browser." +#: static/webpush/webpush.js:10 static/webpush/webpush.js:172 +msgid "Subscribe to Push Messaging" msgstr "" -#: static/webpush/webpush.js:40 -msgid "Showing notifications are not supported in your browser." +#: static/webpush/webpush.js:33 +msgid "Service workers are not supported in your browser." msgstr "" -#: static/webpush/webpush.js:49 static/webpush/webpush.js:173 -msgid "Subscribe to Push Messaging" +#: static/webpush/webpush.js:41 +msgid "Showing notifications are not supported in your browser." msgstr "" #: static/webpush/webpush.js:51 msgid "Push notifications are blocked by your browser." msgstr "" -#: static/webpush/webpush.js:60 +#: static/webpush/webpush.js:59 msgid "Push notifications are not available in your browser." msgstr "" -#: static/webpush/webpush.js:73 static/webpush/webpush.js:120 -#: static/webpush/webpush.js:181 +#: static/webpush/webpush.js:72 static/webpush/webpush.js:119 +#: static/webpush/webpush.js:180 msgid "Unsubscribe from Push Messaging" msgstr "" -#: static/webpush/webpush.js:76 static/webpush/webpush.js:123 +#: static/webpush/webpush.js:75 static/webpush/webpush.js:122 msgid "Successfully subscribed to push notifications." msgstr "" -#: static/webpush/webpush.js:129 +#: static/webpush/webpush.js:128 msgid "Error while subscribing to push notifications." msgstr "" -#: static/webpush/webpush.js:161 +#: static/webpush/webpush.js:160 msgid "Subscription is not available." msgstr "" -#: static/webpush/webpush.js:174 +#: static/webpush/webpush.js:173 msgid "Successfully unsubscribed from push notifications." msgstr "" -#: static/webpush/webpush.js:182 +#: static/webpush/webpush.js:181 msgid "Error while unsubscribing from push notifications." msgstr "" diff --git a/webpush/locale/es/LC_MESSAGES/django.mo b/webpush/locale/es/LC_MESSAGES/django.mo new file mode 100644 index 0000000..347b714 Binary files /dev/null and b/webpush/locale/es/LC_MESSAGES/django.mo differ diff --git a/webpush/locale/es/LC_MESSAGES/django.po b/webpush/locale/es/LC_MESSAGES/django.po new file mode 100644 index 0000000..16d957f --- /dev/null +++ b/webpush/locale/es/LC_MESSAGES/django.po @@ -0,0 +1,107 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-09-02 17:03-0300\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: admin.py:16 +msgid "Hey" +msgstr "Hola" + +#: admin.py:16 +msgid "Hello World" +msgstr "Hola Mundo" + +#: admin.py:20 +msgid "Test sent successfully" +msgstr "Prueba enviada con éxito" + +#: admin.py:22 +msgid "Deprecated subscription deleted" +msgstr "Suscripción obsoleta eliminada" + +#: admin.py:23 +msgid "Send test message" +msgstr "Enviar mensaje de prueba" + +#: forms.py:8 models.py:14 models.py:38 +msgid "Group" +msgstr "Grupo" + +#: forms.py:10 +msgid "Subscribe" +msgstr "Suscribirse" + +#: forms.py:11 +msgid "Unsubscribe" +msgstr "Desuscribirse" + +#: forms.py:12 +msgid "Status Type" +msgstr "Tipo de estado" + +#: models.py:8 +msgid "Name" +msgstr "Nombre" + +#: models.py:15 +msgid "Groups" +msgstr "Grupos" + +#: models.py:20 +msgid "Browser" +msgstr "Navegador" + +#: models.py:21 +msgid "User Agent" +msgstr "Agente de usuario" + +#: models.py:22 +msgid "Endpoint" +msgstr "Endpoint" + +#: models.py:23 +msgid "Auth" +msgstr "Autenticación" + +#: models.py:24 +msgid "P256DH" +msgstr "P256DH" + +#: models.py:30 +msgid "Subscription Info" +msgstr "Información de suscripción" + +#: models.py:31 +msgid "Subscription Infos" +msgstr "Informaciones de suscripción" + +#: models.py:36 +msgid "User" +msgstr "Usuario" + +#: models.py:37 +msgid "Subscription" +msgstr "Suscripción" + +#: models.py:47 +msgid "At least user or group should be present" +msgstr "Debe haber al menos un usuario o grupo presente" + +#: models.py:56 models.py:57 +msgid "Push Information" +msgstr "Información de notificación" diff --git a/webpush/locale/es/LC_MESSAGES/djangojs.mo b/webpush/locale/es/LC_MESSAGES/djangojs.mo new file mode 100644 index 0000000..eab77fa Binary files /dev/null and b/webpush/locale/es/LC_MESSAGES/djangojs.mo differ diff --git a/webpush/locale/es/LC_MESSAGES/djangojs.po b/webpush/locale/es/LC_MESSAGES/djangojs.po new file mode 100644 index 0000000..8804a72 --- /dev/null +++ b/webpush/locale/es/LC_MESSAGES/djangojs.po @@ -0,0 +1,64 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2024-09-02 17:03-0300\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: static/webpush/webpush.js:10 static/webpush/webpush.js:172 +msgid "Subscribe to Push Messaging" +msgstr "Suscribirse a la mensajería push" + +#: static/webpush/webpush.js:33 +msgid "Service workers are not supported in your browser." +msgstr "Los service workers no son compatibles con tu navegador." + +#: static/webpush/webpush.js:41 +msgid "Showing notifications are not supported in your browser." +msgstr "Mostrar notificaciones no es compatible con tu navegador." + +#: static/webpush/webpush.js:51 +msgid "Push notifications are blocked by your browser." +msgstr "Las notificaciones push están bloqueadas por tu navegador." + +#: static/webpush/webpush.js:59 +msgid "Push notifications are not available in your browser." +msgstr "Las notificaciones push no están disponibles en tu navegador." + +#: static/webpush/webpush.js:72 static/webpush/webpush.js:119 +#: static/webpush/webpush.js:180 +msgid "Unsubscribe from Push Messaging" +msgstr "Darse de baja de la mensajería push" + +#: static/webpush/webpush.js:75 static/webpush/webpush.js:122 +msgid "Successfully subscribed to push notifications." +msgstr "Suscripción a notificaciones push exitosa." + +#: static/webpush/webpush.js:128 +msgid "Error while subscribing to push notifications." +msgstr "Error al suscribirse a las notificaciones push." + +#: static/webpush/webpush.js:160 +msgid "Subscription is not available." +msgstr "La suscripción no está disponible." + +#: static/webpush/webpush.js:173 +msgid "Successfully unsubscribed from push notifications." +msgstr "Baja de notificaciones push exitosa." + +#: static/webpush/webpush.js:181 +msgid "Error while unsubscribing from push notifications." +msgstr "Error al darse de baja de las notificaciones push." diff --git a/webpush/migrations/0007_alter_group_options_alter_pushinformation_options_and_more.py b/webpush/migrations/0007_alter_group_options_alter_pushinformation_options_and_more.py new file mode 100644 index 0000000..adc6a0f --- /dev/null +++ b/webpush/migrations/0007_alter_group_options_alter_pushinformation_options_and_more.py @@ -0,0 +1,73 @@ +# Generated by Django 4.2.14 on 2024-11-28 19:48 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('webpush', '0006_alter_subscriptioninfo_user_agent'), + ] + + operations = [ + migrations.AlterModelOptions( + name='group', + options={'ordering': ['name'], 'verbose_name': 'Group', 'verbose_name_plural': 'Groups'}, + ), + migrations.AlterModelOptions( + name='pushinformation', + options={'ordering': ['user', 'group'], 'verbose_name': 'Push Information', 'verbose_name_plural': 'Push Information'}, + ), + migrations.AlterModelOptions( + name='subscriptioninfo', + options={'ordering': ['browser'], 'verbose_name': 'Subscription Info', 'verbose_name_plural': 'Subscription Infos'}, + ), + migrations.AlterField( + model_name='group', + name='name', + field=models.CharField(max_length=255, unique=True, verbose_name='Name'), + ), + migrations.AlterField( + model_name='pushinformation', + name='group', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='webpush_info', to='webpush.group', verbose_name='Group'), + ), + migrations.AlterField( + model_name='pushinformation', + name='subscription', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='webpush_info', to='webpush.subscriptioninfo', verbose_name='Subscription'), + ), + migrations.AlterField( + model_name='pushinformation', + name='user', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='webpush_info', to=settings.AUTH_USER_MODEL, verbose_name='User'), + ), + migrations.AlterField( + model_name='subscriptioninfo', + name='auth', + field=models.CharField(max_length=100, verbose_name='Auth'), + ), + migrations.AlterField( + model_name='subscriptioninfo', + name='browser', + field=models.CharField(max_length=100, verbose_name='Browser'), + ), + migrations.AlterField( + model_name='subscriptioninfo', + name='endpoint', + field=models.URLField(max_length=500, verbose_name='Endpoint'), + ), + migrations.AlterField( + model_name='subscriptioninfo', + name='p256dh', + field=models.CharField(max_length=100, verbose_name='P256DH'), + ), + migrations.AlterField( + model_name='subscriptioninfo', + name='user_agent', + field=models.CharField(blank=True, max_length=500, verbose_name='User Agent'), + ), + ] diff --git a/webpush/models.py b/webpush/models.py index e26c2ab..ae2df89 100644 --- a/webpush/models.py +++ b/webpush/models.py @@ -1,26 +1,41 @@ from django.db import models from django.core.exceptions import FieldError from django.conf import settings - -# Create your models here. +from django.utils.translation import gettext_lazy as _ class Group(models.Model): - name = models.CharField(max_length=255, unique=True) + name = models.CharField(max_length=255, unique=True, verbose_name=_("Name")) + + def __str__(self): + return self.name + + class Meta: + verbose_name = _("Group") + verbose_name_plural = _("Groups") + ordering = ['name'] class SubscriptionInfo(models.Model): - browser = models.CharField(max_length=100) - user_agent = models.CharField(max_length=500, blank=True) - endpoint = models.URLField(max_length=500) - auth = models.CharField(max_length=100) - p256dh = models.CharField(max_length=100) + browser = models.CharField(max_length=100, verbose_name=_("Browser")) + user_agent = models.CharField(max_length=500, blank=True, verbose_name=_("User Agent")) + endpoint = models.URLField(max_length=500, verbose_name=_("Endpoint")) + auth = models.CharField(max_length=100, verbose_name=_("Auth")) + p256dh = models.CharField(max_length=100, verbose_name=_("P256DH")) + + def __str__(self): + return self.browser + + class Meta: + verbose_name = _("Subscription Info") + verbose_name_plural = _("Subscription Infos") + ordering = ['browser'] class PushInformation(models.Model): - user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='webpush_info', blank=True, null=True, on_delete=models.CASCADE) - subscription = models.ForeignKey(SubscriptionInfo, related_name='webpush_info', on_delete=models.CASCADE) - group = models.ForeignKey(Group, related_name='webpush_info', blank=True, null=True, on_delete=models.CASCADE) + user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='webpush_info', blank=True, null=True, on_delete=models.CASCADE, verbose_name=_("User")) + subscription = models.ForeignKey(SubscriptionInfo, related_name='webpush_info', on_delete=models.CASCADE, verbose_name=_("Subscription")) + group = models.ForeignKey(Group, related_name='webpush_info', blank=True, null=True, on_delete=models.CASCADE, verbose_name=_("Group")) def save(self, *args, **kwargs): # Check whether user or the group field is present @@ -29,5 +44,15 @@ def save(self, *args, **kwargs): if self.user or self.group: super(PushInformation, self).save(*args, **kwargs) else: - raise FieldError('At least user or group should be present') + raise FieldError(_('At least user or group should be present')) + + def __str__(self): + if self.group: + return f'{self.group}' + + return f'{self.user}' + class Meta: + verbose_name = _("Push Information") + verbose_name_plural = _("Push Information") + ordering = ['user', 'group'] diff --git a/webpush/views.py b/webpush/views.py index eabc5a6..a6aa482 100644 --- a/webpush/views.py +++ b/webpush/views.py @@ -1,7 +1,7 @@ import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt -from django.views.decorators.http import require_POST, require_GET +from django.views.decorators.http import require_POST from django.views.generic import TemplateView from .forms import WebPushForm, SubscriptionForm