Skip to content

Instantly share code, notes, and snippets.

@Ruhshan
Created November 11, 2016 14:13
Show Gist options
  • Save Ruhshan/54038e42a33599f09db6e3a65271a611 to your computer and use it in GitHub Desktop.
Save Ruhshan/54038e42a33599f09db6e3a65271a611 to your computer and use it in GitHub Desktop.
#___________myproject/settings.py__________
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'anotherapp',
'activitystream'
]
#In the project's setting we can see two new apps, one in activitystream, other one is
#some another app which have an employee module
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'activitystream.activity_middleware.ActivityMiddleware',
]
#'activitystream.activity_middleware.ActivityMiddleware' is a middleware that detects changes in Employee
#module and takes specified actions
#........................................................
#___________activitystream/models.py__________
from __future__ import unicode_literals
from django.db import models
class Stream(models.Model):
value=models.CharField(max_length=200)
def __str__(self):
return self.value
#activity stream app has a single model stream, that has a column named value, where activity log is stored
#as string
#...........................................................
#___________activitystream/activity_middleware.py__________
from anotherapp.models import Employee
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from datetime import date
from .models import Stream
uname=""
def ActivityMiddleware(get_response):
def middleware(request):
global uname
uname=request.user.username
response = get_response(request)
return response
return middleware
@receiver(post_save, sender=Employee)
def save_handler(sender, instance, created, **kwargs):
if created==True:
message="Employee {} has been added by {} at {}".format(instance,uname,date.today())
s=Stream(value=message)
s.save()
else:
message="Employee {} has been updated by {} at {}".format(instance,uname,date.today())
s=Stream(value=message)
s.save()
@receiver(pre_delete, sender=Employee)
def delete_handler(sender, instance, **kwargs):
message="Employee {} has been deleted by {} at {}".format(instance,uname,date.today())
s=Stream(value=message)
s.save()
#this middleware detect post_save and pre_delete signal from Employee module of anotherapp, and updates
#Keeps a message about the change in the stream model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment