Will & Skill Developers

Will & Skill Developers

Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Hassan Mian

Don't let someone else's opinion of you become your reality. - Les Brown


Real Time Notifications with Firebase, Django and Backbone - Part 2

Hassan MianHassan Mian

Quick recap from part 1:

In this part we will cover the following:

Let's carry on with a post_save method as well. We usually put our notification logic in a file called "notifications.py". Let's create it:

First of all I'll go through all the classes and functions we import:

from django.conf import settings
from django.template.loader import render_to_string

from core.tasks.notifications import send_notifications    

from django.conf import settings - We import our settings for debugging purposes.

from django.template.loader import render_to_string - A simple function we will use when we want to render our django template and send it to our real time notification Back-End, Firebase.

from core.tasks.notifications import send_notifications - We have a function that we haven't written yet. We usually put our global function in an app called core. Further on we will create a folder called tasks in that app and then a file called notifications.py. This file will handle our notifications.

def create_notification(sender, created, **kwargs):
  if created:
      model = kwargs['instance']
      subscribers = model.get_subscribers()
      context = {
          'model': model,
          'frontend_uri': '/app/#/posts',
          'SITE_URL': settings.SITE_URL
      notification_markup = render_to_string('notifications/blogify/post_notification.html', context)

      send_notifications(subscribers, notification_markup)

So whats happening here?

First of all we see that our signal sends 3 input variables: sender, created and kwargs.

And that we simply check if the model was created or updated. In this case we just want to send out a notification when the model is created.

Next we get our model and fetch our subscribers.
Use a context variable to structure some data that we will use to render our template. modelis quite self explanatory, frontend_uri is the link the user will be redirected to when clicking on the notification. SITE_URL is the root url. Not needed for desktop notification but I've included it here if we want to add email notification to our cool project aswell.

Now we need to render our template. I've created a simple notification template. You could easily edit this and make it as advanced as needed for your project:

<div data-href="{{ frontend_uri }}">
    {{model.author.get_full_name}} just created a new Blog post - "{{ model.title }}".

Lastly we take our subscribers and our rendered template and send it to our notification distributor: ```send_notifications````

I'll cover that in the next part.

Take me to that next part

Hassan Mian

Hassan Mian

Don't let someone else's opinion of you become your reality. - Les Brown