Reputation: 47
I'm a beginner at Django.
Referring to this link, I installed fcm-django and finished setting. fcm-django doc
fcm-djagno
.pip install fcm-django
fcm-django
on settings.py
.import firebase_admin
from firebase_admin import credentials
cred_path = os.path.join(BASE_DIR, "serviceAccountKey.json")
cred = credentials.Certificate(cred_path)
firebase_admin.initialize_app(cred)
...
INSTALLED_APPS = [
...
'fcm_django',
]
...
FCM_DJANGO_SETTINGS = {
# default: _('FCM Django')
"APP_VERBOSE_NAME": "django_fcm",
# Your firebase API KEY
"FCM_SERVER_KEY": "AAAAsM1f8bU:APA91bELsdJ8WaSy...",
# true if you want to have only one active device per registered user at a time
# default: False
"ONE_DEVICE_PER_USER": False,
# devices to which notifications cannot be sent,
# are deleted upon receiving error response from FCM
# default: False
"DELETE_INACTIVE_DEVICES": True,
}
And, when I post notice, if push is active, I try to send push notifications to all devices.
from firebase_admin.messaging import Message, Notification
from fcm_django.models import FCMDevice
class noticeCreateView(View):
def post(self, request, *args, **kwargs):
title = request.POST.get('title')
content = request.POST.get('content')
push = request.POST.get('push')
if push:
message = Message(
notification=Notification(
title=title,
body=sentence,
),
)
try:
devices = FCMDevice.objects.all()
devices.send_message(message)
except Exception as e:
print('Push notification failed.', e)
return HttpResponseRedirect(reverse('notice_list'))
What I am curious about is whether data is automatically added in the FCMDevice model when the user installs this app.
If I have to generate data manually, I wonder how to get an FCM registration token and how to implement adding data to the FCMDevice model.
Upvotes: 5
Views: 4523
Reputation: 37
I had the same issue for a while and found a way to fix this. after all configurations of django-fcm, when the user login/signup create a device instance of FCMDevice and save user to that instance.
refer pyrebase for creating registration_id(token)
IN VIEWS from fcm_django.models import FCMDevice
fcm_device = FCMDevice()
fcm_device.registration_id = registration_id
fcm_device.user = user
fcm_device.save()
Upvotes: 3