Repository: akvo/akvo-rsr

Issue:
Can't delete projects
## Test plan

GIVEN the RSR project admin
WHEN a user deletes a project
THEN no IntegrityError should be shown
AND the project should be deleted accordingly

GIVEN the My projects page in MyRSR
WHEN a user clicks the 'Create new project' button
AND the project editor for the new project is opened
THEN the RSR validation set should be selected by default
## Issue description

The new validation models make it impossible to delete projects. When trying to do it in the admin I get the following error:

IntegrityError at /en/admin/rsr/project/1516/delete/

insert or update on table "rsr_project_validations" violates foreign key constraint "rsr_project_valida_project_id_2ae411aff8f8055_fk_rsr_project_id"
DETAIL:  Key (project_id)=(1516) is not present in table "rsr_project".

Deleting the offending constraint allows deleting. I haven't looked deeper into the problem than that...

![screenshot_97](https://cloud.githubusercontent.com/assets/142613/12017582/dd0b94a4-ad58-11e5-812d-e9f2d7a9d567.png)



Discussion:
Additional info. When I remove the index to be able to delete I get two deletion notices in the admin:
![screenshot_98](https://cloud.githubusercontent.com/assets/142613/12031594/2ef7afae-ae0e-11e5-9ace-1504fa86d255.png)
This is fishy, and might be connected to the original problem.

This is due to a saving action after the project has been deleted from the DB. See these lines: https://github.com/akvo/akvo-rsr/blob/develop/akvo/rsr/models/project.py#L388-L391


Resolving patch:
diff --git a/akvo/rsr/models/project.py b/akvo/rsr/models/project.py
--- a/akvo/rsr/models/project.py
+++ b/akvo/rsr/models/project.py
@@ -10,6 +10,7 @@
 
 from django.conf import settings
 from django.core.exceptions import ValidationError, ObjectDoesNotExist
+from django.core.mail import send_mail
 from django.core.validators import MaxValueValidator, MinValueValidator
 from django.db import models
 from django.db.models import get_model, Max, Sum
@@ -326,7 +327,7 @@ class Project(TimestampsMixin, models.Model):
 
     # Project editor settings
     validations = models.ManyToManyField(
-        ProjectEditorValidationSet, verbose_name=_(u'validations'), related_name='projects',
+        ProjectEditorValidationSet, verbose_name=_(u'validations'), related_name='projects'
     )
 
     # denormalized data
@@ -385,11 +386,6 @@ def save(self, last_updated=False, *args, **kwargs):
 
         super(Project, self).save(*args, **kwargs)
 
-        # Add RSR validation set to projects that don't have that set
-        rsr_validation_set = ProjectEditorValidationSet.objects.get(pk=1)
-        if not rsr_validation_set in self.validations.all():
-            self.validations.add(rsr_validation_set)
-
     def clean(self):
         # Don't allow a start date before an end date
         if self.date_start_planned and self.date_end_planned and \
@@ -1174,6 +1170,24 @@ def has_indicators(self):
         return False
 
 
+@receiver(post_save, sender=Project)
+def default_validation_set(sender, **kwargs):
+    """When the project is created, add the RSR validation (pk=1) to the project."""
+    project = kwargs['instance']
+    created = kwargs['created']
+    if created:
+        try:
+            if not project.validations.all():
+                project.validations.add(ProjectEditorValidationSet.objects.get(pk=1))
+        except ProjectEditorValidationSet.DoesNotExist:
+            # RSR validation set does not exist, should not happen..
+            send_mail('RSR validation set missing',
+                      'This is a notification to inform the RSR admins that the RSR validation set '
+                      '(pk=1) is missing.',
+                      getattr(settings, "DEFAULT_FROM_EMAIL", "noreply@akvo.org"),
+                      getattr(settings, "SUPPORT_EMAIL", ['rsr@akvo.org']))
+
+
 @receiver(post_save, sender=ProjectUpdate)
 def update_denormalized_project(sender, **kwargs):
     "Updates the denormalized project.last_update on related project."


Test patch: