From 13a9150f840ac00e0590c973ca34973b15f305b5 Mon Sep 17 00:00:00 2001
From: "J.-S. Caux" <J.S.Caux@uva.nl>
Date: Sun, 30 Sep 2018 10:59:36 +0200
Subject: [PATCH] Improve Profile form validation (prevent duplicates)

---
 profiles/forms.py | 14 ++++++++++++++
 profiles/views.py |  3 ++-
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/profiles/forms.py b/profiles/forms.py
index 3d9c92da6..cdb1a8e1d 100644
--- a/profiles/forms.py
+++ b/profiles/forms.py
@@ -15,6 +15,20 @@ class ProfileForm(forms.ModelForm):
                   'discipline', 'expertises', 'orcid_id', 'webpage',
                   'accepts_SciPost_emails', 'accepts_refereeing_requests']
 
+    def clean_email(self):
+        """
+        Check that the email isn't yet associated to an existing Profile
+        (via either the email field or the m2m-related alternativeemails).
+        """
+        cleaned_email = self.cleaned_data['email']
+        if Profile.objects.filter(email=cleaned_email).exists:
+            raise forms.ValidationError(
+                'A Profile with this email (as primary email) already exists.')
+        elif Profile.objects.filter(alternativeemails__in=cleaned_email).exists():
+            raise forms.ValidationError(
+                'A Profile with this email (as alternative email) already exists.')
+        return cleaned_email
+
 
 class AlternativeEmailForm(forms.ModelForm):
 
diff --git a/profiles/views.py b/profiles/views.py
index 3eaa6658b..d4a122f61 100644
--- a/profiles/views.py
+++ b/profiles/views.py
@@ -104,7 +104,8 @@ class ProfileListView(PermissionsMixin, ListView):
         context['subject_areas'] = SCIPOST_SUBJECT_AREAS
         contributors_wo_profile = Contributor.objects.filter(profile=None)
         context['nr_contributors_wo_profile'] = contributors_wo_profile.count()
-        context['next_contributor_wo_profile'] = random.choice(contributors_wo_profile)
+        #context['next_contributor_wo_profile'] = random.choice(contributors_wo_profile)
+        context['next_contributor_wo_profile'] = contributors_wo_profile.first()
         context['alternative_email_form'] = AlternativeEmailForm()
         return context
 
-- 
GitLab