How send Firebase Push notification in django

10,214

Solution 1

pip install pyfcm

OR

pip install git+https://github.com/olucurious/PyFCM.git

# Send to single device.
from pyfcm import FCMNotification

push_service = FCMNotification(api_key="<api-key>")

registration_id = "<device registration_id>"
message_title = "Uber update"
message_body = "Hi john, your customized news for today is ready"
result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)
print result

OR

# Send to multiple devices by passing a list of ids.
registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...]
message_title = "Uber update"
message_body = "Hope you're having fun this weekend, don't forget to check today's news"
result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)

print result

after google myself getting this result and its working for more info use this link https://pypi.org/project/pyfcm/0.0.4/

Solution 2

They are the methods to send msg or notification. you have to call these methods in your views whenever you have to send msg.

you can create a common method

from fcm_django.models import FCMDevice
def send_notification(user_id, title, message, data):
    try:
        device = FCMDevice.objects.filter(user=user_id).last()
        result = device.send_message(title=title, body=message, data=data, 
           sound=True)
        return result
    except:
        pass

and add call this method whenever you have to send msg or notification.

send_notification(user_id=1, title="Order Return", message="your
    message", data=None)
Share:
10,214

Related videos on Youtube

Sohail Ahmad
Author by

Sohail Ahmad

Working on Django, Angular, Node.js and MongoDB heaving an experience on PHP Codeigniter (MVC) framework, web apps, web services, and Open cart

Updated on June 04, 2022

Comments

  • Sohail Ahmad
    Sohail Ahmad almost 2 years

    I have followed the steps.

    • pip install fcm-django

    Edit your settings.py file

    INSTALLED_APPS = ("fcm_django")
    
    FCM_DJANGO_SETTINGS = {
            "FCM_SERVER_KEY": "[your api key]"
    }
    

    and then

    • manage.py migrate

    How do I send push messages on tokens ?? I didn't understand the following method

    from fcm_django.models import FCMDevice
    device = FCMDevice.objects.all().first()
    device.send_message("Title", "Message")
    device.send_message(data={"test": "test"})
    device.send_message(title="Title", body="Message", icon=..., data={"test": "test"})
    
  • Ravi
    Ravi almost 3 years
    Getting error : type object 'Retry' has no attribute 'DEFAULT_ALLOWED_METHODS' using python 3.8 version. Any help would be appreciated.