commit b436bd510bf4e3e1c69f1c5b699d93171836b798
Author: Stauros Kroustouris <staurosk@noc.grnet.gr>
Date:   Thu Jan 8 16:33:46 2015 +0200

    code cleanup, signals

diff --git a/ChangeLog b/ChangeLog
index af7fe93..1c3a8d2 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,7 +1,9 @@
 ===========
 1.1.2 RELEASE
 Updates and enhancements. Check documentation for updating from previous versions
+
 	- Rest Api
+	- Use Django signals for notifications
 
 =======
 1.1.1 RELEASE
diff --git a/flowspec/helpers.py b/flowspec/helpers.py
new file mode 100644
index 0000000..9255ea7
--- /dev/null
+++ b/flowspec/helpers.py
@@ -0,0 +1,23 @@
+from django.core.mail.message import EmailMessage
+from django.conf import settings
+
+
+def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
+    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
+
+
+def get_peer_techc_mails(user):
+    mail = []
+    additional_mail = []
+    techmails_list = []
+    user_mail = '%s' % user.email
+    user_mail = user_mail.split(';')
+    techmails = user.get_profile().peer.techc_emails.all()
+    if techmails:
+        for techmail in techmails:
+            techmails_list.append(techmail.email)
+    if settings.NOTIFY_ADMIN_MAILS:
+        additional_mail = settings.NOTIFY_ADMIN_MAILS
+    mail.extend(additional_mail)
+    mail.extend(techmails_list)
+    return mail
diff --git a/flowspec/migrations/0006_auto__add_field_route_requesters_address.py b/flowspec/migrations/0006_auto__add_field_route_requesters_address.py
new file mode 100644
index 0000000..f43a104
--- /dev/null
+++ b/flowspec/migrations/0006_auto__add_field_route_requesters_address.py
@@ -0,0 +1,113 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding field 'Route.requesters_address'
+        db.add_column(u'route', 'requesters_address',
+                      self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True),
+                      keep_default=False)
+
+
+    def backwards(self, orm):
+        # Deleting field 'Route.requesters_address'
+        db.delete_column(u'route', 'requesters_address')
+
+
+    models = {
+        'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        'auth.permission': {
+            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        'auth.user': {
+            'Meta': {'object_name': 'User'},
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+        },
+        'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        'flowspec.fragmenttype': {
+            'Meta': {'object_name': 'FragmentType'},
+            'fragmenttype': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+        },
+        'flowspec.matchdscp': {
+            'Meta': {'object_name': 'MatchDscp', 'db_table': "u'match_dscp'"},
+            'dscp': ('django.db.models.fields.CharField', [], {'max_length': '24'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+        },
+        'flowspec.matchport': {
+            'Meta': {'object_name': 'MatchPort', 'db_table': "u'match_port'"},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'port': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '24'})
+        },
+        'flowspec.matchprotocol': {
+            'Meta': {'object_name': 'MatchProtocol', 'db_table': "u'match_protocol'"},
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'protocol': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '24'})
+        },
+        'flowspec.route': {
+            'Meta': {'object_name': 'Route', 'db_table': "u'route'"},
+            'applier': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
+            'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'destination': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
+            'destinationport': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'matchDestinationPort'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['flowspec.MatchPort']"}),
+            'dscp': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['flowspec.MatchDscp']", 'null': 'True', 'blank': 'True'}),
+            'expires': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2015, 1, 15, 0, 0)'}),
+            'filed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+            'fragmenttype': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['flowspec.FragmentType']", 'null': 'True', 'blank': 'True'}),
+            'icmpcode': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'icmptype': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
+            'name': ('django.db.models.fields.SlugField', [], {'max_length': '128'}),
+            'packetlength': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
+            'port': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'matchPort'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['flowspec.MatchPort']"}),
+            'protocol': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['flowspec.MatchProtocol']", 'null': 'True', 'blank': 'True'}),
+            'requesters_address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'response': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'}),
+            'source': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
+            'sourceport': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'matchSourcePort'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['flowspec.MatchPort']"}),
+            'status': ('django.db.models.fields.CharField', [], {'default': "'PENDING'", 'max_length': '20', 'null': 'True', 'blank': 'True'}),
+            'tcpflag': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
+            'then': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['flowspec.ThenAction']", 'symmetrical': 'False'})
+        },
+        'flowspec.thenaction': {
+            'Meta': {'ordering': "['action', 'action_value']", 'unique_together': "(('action', 'action_value'),)", 'object_name': 'ThenAction', 'db_table': "u'then_action'"},
+            'action': ('django.db.models.fields.CharField', [], {'max_length': '60'}),
+            'action_value': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
+        }
+    }
+
+    complete_apps = ['flowspec']
\ No newline at end of file
diff --git a/flowspec/models.py b/flowspec/models.py
index 5f2f455..11a1f1d 100644
--- a/flowspec/models.py
+++ b/flowspec/models.py
@@ -20,13 +20,18 @@
 from django.db import models
 from django.conf import settings
 from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
+from django.db.models.signals import post_save
 from django.utils.translation import ugettext_lazy as _
+from django.core.urlresolvers import reverse
+
+from flowspec.helpers import send_new_mail, get_peer_techc_mails
 from utils import proxy as PR
 from ipaddr import *
 import datetime
 import logging
 from time import sleep
-from junos import create_junos_name, policer_name
+from junos import create_junos_name
 
 import beanstalkc
 from utils.randomizer import id_generator as id_gen
@@ -167,7 +172,7 @@ class Route(models.Model):
     expires = models.DateField(default=days_offset, verbose_name=_("Expires"))
     response = models.CharField(max_length=512, blank=True, null=True, verbose_name=_("Response"))
     comments = models.TextField(null=True, blank=True, verbose_name=_("Comments"))
-
+    requesters_address = models.CharField(max_length=255, blank=True, null=True)
 
     def __unicode__(self):
         return self.name
@@ -183,7 +188,6 @@ class Route(models.Model):
             self.name = "%s_%s" %(self.name, hash)
         super(Route, self).save(*args, **kwargs) # Call the "real" save() method.
 
-
     def clean(self, *args, **kwargs):
         from django.core.exceptions import ValidationError
         if self.destination:
@@ -201,26 +205,125 @@ class Route(models.Model):
 
     def commit_add(self, *args, **kwargs):
         peer = self.applier.get_profile().peer.peer_tag
-        send_message("[%s] Adding rule %s. Please wait..." %(self.applier.username, self.name), peer)
+        send_message("[%s] Adding rule %s. Please wait..." % (self.applier.username, self.name), peer)
         response = add.delay(self)
-        logger.info("Got add job id: %s" %response)
+        logger.info('Got add job id: %s' % response)
+        fqdn = Site.objects.get_current().domain
+        admin_url = 'https://%s%s' % (
+            fqdn,
+            reverse('edit-route', kwargs={'route_slug': self.name})
+        )
+        mail_body = render_to_string(
+            'rule_action.txt',
+            {
+                'route': self,
+                'address': self.requesters_address,
+                'action': 'creation',
+                'url': admin_url
+            }
+        )
+        user_mail = '%s' % self.applier.email
+        user_mail = user_mail.split(';')
+        send_new_mail(
+            settings.EMAIL_SUBJECT_PREFIX + 'Rule %s creation request submitted by %s' % (self.name, self.applier.username),
+            mail_body,
+            settings.SERVER_EMAIL, user_mail,
+            get_peer_techc_mails(self.applier)
+        )
+        d = {
+            'clientip': '%s' % self.requesters_address,
+            'user': self.applier.username
+        }
+        logger.info(mail_body, extra=d)
 
     def commit_edit(self, *args, **kwargs):
         peer = self.applier.get_profile().peer.peer_tag
-        send_message("[%s] Editing rule %s. Please wait..." %(self.applier.username, self.name), peer)
+        send_message(
+            '[%s] Editing rule %s. Please wait...' %
+            (
+                self.applier.username,
+                self.name
+            ), peer
+        )
         response = edit.delay(self)
-        logger.info("Got edit job id: %s" %response)
+        logger.info('Got edit job id: %s' % response)
+        fqdn = Site.objects.get_current().domain
+        admin_url = 'https://%s%s' % (
+            fqdn,
+            reverse(
+                'edit-route',
+                kwargs={'route_slug': self.name}
+            )
+        )
+        mail_body = render_to_string(
+            'rule_action.txt',
+            {
+                'route': self,
+                'address': self.requesters_address,
+                'action': 'edit',
+                'url': admin_url
+            }
+        )
+        user_mail = '%s' % self.applier.email
+        user_mail = user_mail.split(';')
+        send_new_mail(
+            settings.EMAIL_SUBJECT_PREFIX + 'Rule %s edit request submitted by %s' % (self.name, self.applier.username),
+            mail_body, settings.SERVER_EMAIL, user_mail,
+            get_peer_techc_mails(self.applier)
+        )
+        d = {
+            'clientip': self.requesters_address,
+            'user': self.applier.username
+        }
+        logger.info(mail_body, extra=d)
 
     def commit_delete(self, *args, **kwargs):
         reason_text = ''
         reason = ''
         if "reason" in kwargs:
             reason = kwargs['reason']
-            reason_text = "Reason: %s. " %reason
+            reason_text = 'Reason: %s.' % reason
         peer = self.applier.get_profile().peer.peer_tag
-        send_message("[%s] Suspending rule %s. %sPlease wait..." %(self.applier.username, self.name, reason_text), peer)
+        send_message(
+            '[%s] Suspending rule %s. %sPlease wait...' % (
+                self.applier.username,
+                self.name,
+                reason_text
+            ), peer
+        )
         response = delete.delay(self, reason=reason)
-        logger.info("Got delete job id: %s" %response)
+        logger.info('Got delete job id: %s' % response)
+        fqdn = Site.objects.get_current().domain
+        admin_url = 'https://%s%s' % (
+            fqdn,
+            reverse(
+                'edit-route',
+                kwargs={'route_slug': self.name}
+            )
+        )
+        mail_body = render_to_string(
+            'rule_action.txt',
+            {
+                'route': self,
+                'address': self.requesters_address,
+                'action': 'removal',
+                'url': admin_url
+            }
+        )
+        user_mail = '%' % self.applier.email
+        user_mail = user_mail.split(';')
+        send_new_mail(
+            settings.EMAIL_SUBJECT_PREFIX + 'Rule %s removal request submitted by %s' % (self.name, self.applier.username),
+            mail_body,
+            settings.SERVER_EMAIL,
+            user_mail,
+            get_peer_techc_mails(self.applier)
+        )
+        d = {
+            'clientip': self.requesters_address,
+            'user': self.applier.username
+        }
+        logger.info(mail_body, extra=d)
 
     def has_expired(self):
         today = datetime.date.today()
@@ -242,7 +345,7 @@ class Route(models.Model):
         except Exception as e:
             self.status = "EXPIRED"
             self.save()
-            logger.error("No routing options on device. Exception: %s" %e)
+            logger.error('No routing options on device. Exception: %s' % e)
             return True
         for route in routes:
             if route.name == self.name:
@@ -478,3 +581,16 @@ def send_message(msg, user):
     tube_message = json.dumps({'message': str(msg), 'username':peer})
     b.put(tube_message)
     b.close()
+
+
+def notify_user(sender, instance, created, **kwargs):
+    if created:
+        instance.commit_add()
+    else:
+        if instance.has_expired():
+            instance.commit_delete()
+        else:
+            instance.commit_edit()
+
+
+post_save.connect(notify_user, sender=Route)
diff --git a/flowspec/views.py b/flowspec/views.py
index 44c5f36..341ebe7 100644
--- a/flowspec/views.py
+++ b/flowspec/views.py
@@ -54,8 +54,8 @@ from utils.decorators import shib_required
 
 from django.views.decorators.cache import never_cache
 from django.conf import settings
-from django.core.mail.message import EmailMessage
 from django.template.defaultfilters import slugify
+from flowspec.helpers import send_new_mail, get_peer_techc_mails
 import datetime
 import os
 
@@ -127,6 +127,7 @@ def group_routes_ajax(request):
     jresp['aaData'] = routes
     return HttpResponse(json.dumps(jresp), mimetype='application/json')
 
+
 @login_required
 @never_cache
 def overview_routes_ajax(request):
@@ -147,6 +148,7 @@ def overview_routes_ajax(request):
     jresp['aaData'] = routes
     return HttpResponse(json.dumps(jresp), mimetype='application/json')
 
+
 def build_routes_json(groutes):
     routes = []
     for r in groutes:
@@ -170,6 +172,7 @@ def build_routes_json(groutes):
         routes.append(rd)
     return routes
 
+
 @login_required
 @never_cache
 def add_route(request):
@@ -178,9 +181,12 @@ def add_route(request):
     if request.user.is_superuser:
         applier_peer_networks = PeerRange.objects.all()
     if not applier_peer_networks:
-         messages.add_message(request, messages.WARNING,
-                             _("Insufficient rights on administrative networks. Cannot add rule. Contact your administrator"))
-         return HttpResponseRedirect(reverse("group-routes"))
+        messages.add_message(
+            request,
+            messages.WARNING,
+            ('Insufficient rights on administrative networks. Cannot add rule. Contact your administrator')
+        )
+        return HttpResponseRedirect(reverse("group-routes"))
     if request.method == "GET":
         form = RouteForm(initial={'applier': applier})
         if not request.user.is_superuser:
@@ -201,35 +207,30 @@ def add_route(request):
                 pass
         form = RouteForm(request_data)
         if form.is_valid():
-            route=form.save(commit=False)
+            route = form.save(commit=False)
             if not request.user.is_superuser:
                 route.applier = request.user
             route.status = "PENDING"
             route.response = "Applying"
-            route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
-            route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
+            route.source = IPNetwork('%s/%s' % (IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
+            route.destination = IPNetwork('%s/%s' % (IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
+            route.requesters_address = request.META['HTTP_X_FORWARDED_FOR']
             route.save()
             form.save_m2m()
-            route.commit_add()
-            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
-            fqdn = Site.objects.get_current().domain
-            admin_url = "https://%s%s" % (fqdn, reverse("edit-route", kwargs={'route_slug': route.name }))
-            mail_body = render_to_string("rule_action.txt",
-                                             {"route": route, "address": requesters_address, "action": "creation", "url": admin_url})
-            user_mail = "%s" %route.applier.email
-            user_mail = user_mail.split(';')
-            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s creation request submitted by %s" %(route.name, route.applier.username),
-                              mail_body, settings.SERVER_EMAIL, user_mail,
-                              get_peer_techc_mails(route.applier))
-            d = { 'clientip' : "%s"%requesters_address, 'user' : route.applier.username }
-            logger.info(mail_body, extra=d)
             return HttpResponseRedirect(reverse("group-routes"))
         else:
             if not request.user.is_superuser:
                 form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
                 form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
-            return render_to_response('apply.html', {'form': form, 'applier':applier},
-                                      context_instance=RequestContext(request))
+            return render_to_response(
+                'apply.html',
+                {
+                    'form': form,
+                    'applier': applier
+                },
+                context_instance=RequestContext(request)
+            )
+
 
 @login_required
 @never_cache
@@ -239,8 +240,11 @@ def edit_route(request, route_slug):
     route_edit = get_object_or_404(Route, name=route_slug)
     route_edit_applier_peer = route_edit.applier.get_profile().peer
     if applier_peer != route_edit_applier_peer and (not request.user.is_superuser):
-        messages.add_message(request, messages.WARNING,
-                             _("Insufficient rights to edit rule %s") %(route_slug))
+        messages.add_message(
+            request,
+            messages.WARNING,
+            ('Insufficient rights to edit rule %s') % (route_slug)
+        )
         return HttpResponseRedirect(reverse("group-routes"))
 #    if route_edit.status == "ADMININACTIVE" :
 #        messages.add_message(request, messages.WARNING,
@@ -250,9 +254,12 @@ def edit_route(request, route_slug):
 #        messages.add_message(request, messages.WARNING,
 #                             "Cannot edit the expired rule %s. Contact helpdesk to enable it" %(route_slug))
 #        return HttpResponseRedirect(reverse("group-routes"))
-    if route_edit.status == "PENDING" :
-        messages.add_message(request, messages.WARNING,
-                             _("Cannot edit a pending rule: %s.") %(route_slug))
+    if route_edit.status == 'PENDING':
+        messages.add_message(
+            request,
+            messages.WARNING,
+            ('Cannot edit a pending rule: %s.') % (route_slug)
+        )
         return HttpResponseRedirect(reverse("group-routes"))
     route_original = deepcopy(route_edit)
     if request.POST:
@@ -265,11 +272,14 @@ def edit_route(request, route_slug):
                 del request_data['issuperuser']
             except:
                 pass
-        form = RouteForm(request_data, instance = route_edit)
+        form = RouteForm(
+            request_data,
+            instance=route_edit
+        )
         critical_changed_values = ['source', 'destination', 'sourceport', 'destinationport', 'port', 'protocol', 'then', 'fragmenttype']
         if form.is_valid():
             changed_data = form.changed_data
-            route=form.save(commit=False)
+            route = form.save(commit=False)
             route.name = route_original.name
             route.status = route_original.status
             route.response = route_original.response
@@ -278,34 +288,30 @@ def edit_route(request, route_slug):
             if bool(set(changed_data) & set(critical_changed_values)) or (not route_original.status == 'ACTIVE'):
                 route.status = "PENDING"
                 route.response = "Applying"
-                route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
-                route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
+                route.source = IPNetwork('%s/%s' % (IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
+                route.destination = IPNetwork('%s/%s' % (IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
+                route.requesters_address = self.request.META['HTTP_X_FORWARDED_FOR']
             route.save()
             if bool(set(changed_data) & set(critical_changed_values)) or (not route_original.status == 'ACTIVE'):
                 form.save_m2m()
-                route.commit_edit()
-                requesters_address = request.META['HTTP_X_FORWARDED_FOR']
-                fqdn = Site.objects.get_current().domain
-                admin_url = "https://%s%s" % (fqdn, reverse("edit-route", kwargs={'route_slug': route.name }))
-                mail_body = render_to_string("rule_action.txt",
-                                             {"route": route, "address": requesters_address, "action": "edit", "url": admin_url})
-                user_mail = "%s" %route.applier.email
-                user_mail = user_mail.split(';')
-                send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s edit request submitted by %s" %(route.name, route.applier.username),
-                              mail_body, settings.SERVER_EMAIL, user_mail,
-                              get_peer_techc_mails(route.applier))
-                d = { 'clientip' : requesters_address, 'user' : route.applier.username }
-                logger.info(mail_body, extra=d)
+                # route.commit_edit()
             return HttpResponseRedirect(reverse("group-routes"))
         else:
             if not request.user.is_superuser:
                 form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
                 form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
-            return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
-                                      context_instance=RequestContext(request))
+            return render_to_response(
+                'apply.html',
+                {
+                    'form': form,
+                    'edit': True,
+                    'applier': applier
+                },
+                context_instance=RequestContext(request)
+            )
     else:
         if (not route_original.status == 'ACTIVE'):
-            route_edit.expires = datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
+            route_edit.expires = datetime.date.today() + datetime.timedelta(days=settings.EXPIRATION_DAYS_OFFSET)
         dictionary = model_to_dict(route_edit, fields=[], exclude=[])
         if request.user.is_superuser:
             dictionary['issuperuser'] = request.user.username
@@ -318,8 +324,16 @@ def edit_route(request, route_slug):
         if not request.user.is_superuser:
             form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
             form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
-        return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
-                                  context_instance=RequestContext(request))
+        return render_to_response(
+            'apply.html',
+            {
+                'form': form,
+                'edit': True,
+                'applier': applier
+            },
+            context_instance=RequestContext(request)
+        )
+
 
 @login_required
 @never_cache
@@ -334,25 +348,15 @@ def delete_route(request, route_slug):
             if not request.user.is_superuser:
                 route.applier = request.user
             route.response = "Deactivating"
+            route.requesters_address = request.META['HTTP_X_FORWARDED_FOR']
             route.save()
-            route.commit_delete()
-            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
-            fqdn = Site.objects.get_current().domain
-            admin_url = "https://%s%s" % (fqdn, reverse("edit-route", kwargs={'route_slug': route.name }))
-            mail_body = render_to_string("rule_action.txt",
-                                             {"route": route, "address": requesters_address, "action": "removal", "url": admin_url})
-            user_mail = "%s" %route.applier.email
-            user_mail = user_mail.split(';')
-            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s removal request submitted by %s" %(route.name, route.applier.username),
-                              mail_body, settings.SERVER_EMAIL, user_mail,
-                             get_peer_techc_mails(route.applier))
-            d = { 'clientip' : requesters_address, 'user' : route.applier.username }
-            logger.info(mail_body, extra=d)
+            # route.commit_delete()
         html = "<html><body>Done</body></html>"
         return HttpResponse(html)
     else:
         return HttpResponseRedirect(reverse("group-routes"))
 
+
 @login_required
 @never_cache
 def user_profile(request):
@@ -577,26 +581,6 @@ def load_jscript(request, file):
     return render_to_response('%s.js' % file, {'timeout': long_polling_timeout}, context_instance=RequestContext(request), mimetype="text/javascript")
 
 
-def get_peer_techc_mails(user):
-    mail = []
-    additional_mail = []
-    techmails_list = []
-    user_mail = "%s" %user.email
-    user_mail = user_mail.split(';')
-    techmails = user.get_profile().peer.techc_emails.all()
-    if techmails:
-        for techmail in techmails:
-            techmails_list.append(techmail.email)
-    if settings.NOTIFY_ADMIN_MAILS:
-        additional_mail = settings.NOTIFY_ADMIN_MAILS
-    mail.extend(additional_mail)
-    mail.extend(techmails_list)
-    return mail
-
-def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
-    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
-
-
 def lookupShibAttr(attrmap, requestMeta):
     for attr in attrmap:
         if (attr in requestMeta.keys()):
diff --git a/flowspec/viewsets.py b/flowspec/viewsets.py
index 0938a19..f896960 100644
--- a/flowspec/viewsets.py
+++ b/flowspec/viewsets.py
@@ -36,6 +36,9 @@ class RouteViewSet(viewsets.ModelViewSet):
     queryset = Route.objects.all()
     serializer_class = RouteSerializer
 
+    def pre_save(self, obj):
+        obj.requesters_address = self.request.META['HTTP_X_FORWARDED_FOR']
+
 
 class PortViewSet(viewsets.ModelViewSet):
     queryset = MatchPort.objects.all()
