Django Push Notifications: Full Example for HTML Sites (2023)
Sure! Here's a full example of how you can implement push notifications in a Django application to send updates to an HTML site.\n\n1. Install the required packages:\n \n pip install django-webpush\n \n\n2. Add 'webpush' to your INSTALLED_APPS in the Django settings file.\n\n3. Create a new Django view that will handle the push notification subscription request:\n python\n from django.shortcuts import render\n from webpush import send_user_notification\n\n def subscribe(request):\n if request.method == 'POST':\n subscription_info = request.POST.get('subscription_info')\n send_user_notification(subscription_info, 'Welcome to our site!')\n return render(request, 'subscribe.html')\n \n\n4. Create a new Django template subscribe.html that will handle the push notification subscription form:\n html\n <form method='POST' action='{% url 'subscribe' %}'>\n {% csrf_token %}\n <input type='text' name='subscription_info' placeholder='Enter your subscription info'>\n <button type='submit'>Subscribe</button>\n </form>\n \n\n5. Add the necessary JavaScript code to your HTML site to handle the push notifications:\n javascript\n if ('serviceWorker' in navigator) {\n navigator.serviceWorker.register('/static/js/service-worker.js').then(function(registration) {\n console.log('Service Worker registered with scope:', registration.scope);\n registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: 'Your application server key'\n }).then(function(subscription) {\n var subscriptionInfo = JSON.stringify(subscription);\n // Send the subscription info to your Django view\n fetch('/subscribe/', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-CSRFToken': 'Your CSRF token'\n },\n body: 'subscription_info=' + subscriptionInfo\n });\n }).catch(function(error) {\n console.log('Subscription failed:', error);\n });\n }).catch(function(error) {\n console.log('Service Worker registration failed:', error);\n });\n }\n \n\n6. Finally, add a URL pattern in your Django urls.py file to map the /subscribe/ URL to the subscribe view:\n python\n from django.urls import path\n from .views import subscribe\n\n urlpatterns = [\n path('subscribe/', subscribe, name='subscribe'),\n ]\n \n\nThat's it! Now, when a user visits your HTML site and clicks on the 'Subscribe' button, their subscription info will be sent to the Django view, and a push notification will be sent to their device with the message 'Welcome to our site!'
原文地址: https://www.cveoy.top/t/topic/ptwG 著作权归作者所有。请勿转载和采集!