Django Push Notifications: Full Example & Guide (2023)
Sure! Here's a full example of how you can implement push notifications in a Django application and display them on an HTML site:\n\n1. Install required packages:\n - django-notifications: pip install django-notifications\n\n2. Add notifications to your Django project's INSTALLED_APPS in the settings.py file.\n\n3. Create a new model to store the push notifications in your Django app's models.py file:\n\npython\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass PushNotification(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n message = models.CharField(max_length=255)\n is_read = models.BooleanField(default=False)\n created_at = models.DateTimeField(auto_now_add=True)\n\n\n4. Run migrations to create the necessary database table:\n\nshell\npython manage.py makemigrations\npython manage.py migrate\n\n\n5. Create a new view to handle the push notification logic in your Django app's views.py file:\n\npython\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom .models import PushNotification\n\n@login_required\ndef push_notification(request):\n notifications = PushNotification.objects.filter(user=request.user).order_by('-created_at')\n return render(request, 'notifications.html', {'notifications': notifications})\n\n\n6. Create a new HTML template to display the push notifications, named notifications.html:\n\nhtml\n{% extends 'base.html' %}\n\n{% block content %}\n <h1>Push Notifications</h1>\n <ul>\n {% for notification in notifications %}\n <li{% if notification.is_read %} class="read"{% endif %}>{{ notification.message }}</li>\n {% endfor %}\n </ul>\n{% endblock %}\n\n\n7. Add a URL pattern to your Django app's urls.py file to map the view to a URL:\n\npython\nfrom django.urls import path\nfrom .views import push_notification\n\nurlpatterns = [\n path('notifications/', push_notification, name='push_notification'),\n]\n\n\n8. In your Django app's views or wherever you want to trigger a push notification, create a new instance of the PushNotification model and save it:\n\npython\nfrom .models import PushNotification\nfrom django.contrib.auth.models import User\n\ndef trigger_push_notification(user_id, message):\n user = User.objects.get(id=user_id)\n notification = PushNotification(user=user, message=message)\n notification.save()\n\n\n9. Finally, you can navigate to /notifications in your browser to view the push notifications for the currently logged-in user.\n\nNote: This is a basic example to get you started. You may need to modify the code to suit your specific requirements and styling.
原文地址: https://www.cveoy.top/t/topic/ptpM 著作权归作者所有。请勿转载和采集!