1

I'm a beginner at Django.

Referring to this link, I installed fcm-django and finished setting. fcm-django doc

  • Install fcm-djagno.
pip install fcm-django
  • Setting 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.

4

0 回答 0