What is an activity stream?

It is a sequential chain of all activities done by the users in a website.Like Twitter showing our own feeds ,listing activities of developers on Gitlab dashboard or showing activities of connections on LinkedIn.Whatever you may call it,It is an activity stream.

For ex:

This is the activity stream for some company dashboard.See the smiling faces of company members and their activity beside on their dashboard.If you are a django developer and trying to create similar activity streams,then this post is for you.This post is for everyone who wants to learn how to create LinkedIn like realtime dashboard using powerful Django 1.7 web framework.

How we can implement activity streams?

Actually there are few advanced concepts like signals and handlers in Django using which we can notify anybody at a particular time i.e when user posts a comment ,send it to email etc.Using that basic functionality of signals ,we should work hard to create dashboard activity streams.Fortunately a young Django developer called Justin Quick wrote a quick usable Django plug-in called django-activity-stream to lift the burden from our shoulders in creating activity streams with Django in python.Documentation is pretty good but beginners may confuse about it’s usage.Here is the link to that Django plugin library.

https://github.com/justquick

What are the requirements?

* Python2.7

* Django 1.7> (In lower versions,we need to look into many more things,so install safely 1.7 in virtualenv )

* django-activity-stream

Use the below commands to install Django1.7 in a virtual environment

$ pip install virtualenv $ virtualenv djangoenv

First command install the virtual environment tool and second command creates a virtual environment called djangoenv,in which we are going to install our Django,and its related libraries.Now only environment is created.In order to enter into that environment we need to activate it.

$ source djangoenv/bin/activate

then you will find change in the shell symbol to

(djangoenv)$ ls -l

Now you are in a virtual environment that has a separate copy of python interpreter and fresh libraries to work upon.

Note: In virtual environment use only pip install command instead of sudo pip.

Now let us install django 1.7 ,django-activity-stream

$ pip install Django==1.7.1 $ pip install django-activity-stream

Now everything is ready.

I am creating a new project called “tutorial” and creating an app called “dashboard”.

(djangoenv)$ django-admin.py startproject tutorial (djangoenv)$ cd tutorial (djangoenv)$ django-admin.py startapp dashboard

Now your directory structure should be app inside project directory.I also hope that you have chosen your own back-end.I am continuing with MySQL .First there will not be any users.Create database and then use following commands for creating tables.

(djangoenv)$ ./manage.py makemigrations (djangoenv)$ ./manage.py migrate

makemigrations command scans all your models in apps.So you have a default User model in django.contrib.auth.models.After typing those commands your User table will be created.Now create super user to quick insert data into django models.

(djangoenv)$ django-admin.py createsuperuser

Now after creating the superuser login and populate the users.For me I created 3 users namely,

* naren

* sriman

* manoj

I am going to make users as supervisors.So I create supervisors model and tasks model in my dashboard app.Each supervisor can be allocated with many tasks in hand.

my models.py file looks like

#dashboard.models from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): name = models.CharField(max_length=100) description = models.TextField(null=True,blank=True) class Supervisor(models.Model): user = models.ForeignKey(User,null=True,blank=True,related_name="supervisor") task = models.ManyToManyField(Task,related_name='tasks')

I use foreign key to access user name and one supervisor can have many tasks.So it is a many to many field.

Setting up django-activity-stream?

Your settings.py should consists of following things.Add actstream to list of apps.Add that ACTSTREAM_SETTINGS file to your settings.py file.

#settings.py .... INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', 'actstream', ) ACTSTREAM_SETTINGS = { 'MANAGER': 'dashboard.managers.MyActionManager', 'FETCH_RELATIONS': True, 'USE_PREFETCH': True, 'USE_JSONFIELD': False, 'GFK_FETCH_DEPTH': 1, } ....

Now you need to create three files in order to proceed further.In dashboard craete managers.py, signals.py, apps.py.

#dashboard.managers.py from datetime import datetime from django.contrib.contenttypes.models import ContentType from actstream.managers import ActionManager, stream class MyActionManager(ActionManager): @stream def mystream(self, obj, verb='posted', time=None): if time is None: time = datetime.now() return obj.actor_actions.filter(verb = verb, timestamp__lte = time)

This file is the time stamp manager that creates and returns action generated time.You can write your own logic here if you wish to return other parameters than time.

#dashboard.apps.py from django.apps import AppConfig from actstream import registry from django.contrib.auth.models import User class MyAppConfig(AppConfig): name = 'dashboard' def ready(self): registry.register(User,self.get_model('Task'),self.get_model('Supervisor'))

This apps.py registers the models to the action manager.In order to use activity stream we need to register our models first.So I am registering my User model with dashboard models Task,Supervisor.

Next we need to add one line to __init__.py of dashboard app.These all steps are followed to use activity-stream

default_app_config = 'dashboard.apps.MyAppConfig'

By this we link the AppConfiguration to activity stream’s MyAppConfig.

Now everything is finished and we are ready to go.I am going to create tasks in the shell to concentrate more on creation of activity streams.

I created three tasks and these can be assigned to any supervisor.I am going to assign tasks to supervisors and at the same time activity will be recorded by activity stream.Normally in our projects assigning task to a user will lie in a view.So you need to send an action signal at the time of creation of assignment action.action_handler in actstream.actions handles the storing of these actions.

Using action method we send a signal with actor,verb and target as parameters.These actor,target must be registered before using them.That is what we did above in file dashboard.apps.py .

actor – Source object which is performing action. It is like subject in an English statement.

verb – Verb is the description of the action.

target – Target object is the thing upon action is performed. It is like object in an Enlgish statement.

Now i am going to assign planning task to supervisor naren and instantly sends that signal.

Just see the output 31.It returned me the action object that created.It will be stored in the database.

Let us give tasks for two more Supervisors.

Remeber these assignments can occur anywhere in your views at anytime,but actions are stored in a common queue like object based on the time they created. we can fetch actions from that and list them on the dashboard.

Action is the model that stores all actions generated.Who created model for that ?. django-activity-stream takes care of that.Now we need to list all the occured actions on a page.Just create the dash board view and display all actions in it.

See how the time stamps and all perfectly managed.Just display them on a view.your dash board will be finished.Create more combinations of actions as required and also use full power of django-activity-streams by tweaking all options available

We have tons of options for django-activity-stream like

* fetching actor_stream (actor actions)

* fetching target_stream (target actions)

* fethcing user_stream ( all actions associated with a user)

* following/unfollow certain stream

The full code for the project is available with sqlite db in this link

https://github.com/narenaryan/django-activity-stream-tutorial

🙂 hope you enjoyed the article.