From 70490f597136c77346fe61b2495d3df11e0b4a1c Mon Sep 17 00:00:00 2001
From: "J.-S. Caux" <J.S.Caux@uva.nl>
Date: Mon, 18 Nov 2019 08:14:06 +0100
Subject: [PATCH] Remove organization_lookup

---
 finances/forms.py                    |  8 ++++++-
 forums/forms.py                      |  7 +++++-
 funders/forms.py                     |  7 +++++-
 journals/forms.py                    | 10 +++++++--
 organizations/templatetags/lookup.py | 33 ----------------------------
 organizations/urls.py                |  6 +++++
 organizations/views.py               | 19 ++++++++++++++++
 profiles/forms.py                    |  8 ++++++-
 scipost/forms.py                     | 21 +++++++++++++-----
 9 files changed, 75 insertions(+), 44 deletions(-)
 delete mode 100644 organizations/templatetags/lookup.py

diff --git a/finances/forms.py b/finances/forms.py
index 4fbafdb8d..2bce60b8f 100644
--- a/finances/forms.py
+++ b/finances/forms.py
@@ -10,16 +10,22 @@ from django.db.models import Sum
 from django.utils import timezone
 
 from ajax_select.fields import AutoCompleteSelectField
+from dal import autocomplete
 from dateutil.rrule import rrule, MONTHLY
 
 from common.forms import MonthYearWidget
+from organizations.models import Organization
 from scipost.fields import UserModelChoiceField
 
 from .models import Subsidy, SubsidyAttachment, WorkLog
 
 
 class SubsidyForm(forms.ModelForm):
-    organization = AutoCompleteSelectField('organization_lookup')
+    # organization = AutoCompleteSelectField('organization_lookup')
+    organization = forms..ModelChoiceField(
+        queryset=Organization.objects.all(),
+        widget=autocomplete.ModelSelect2(url='/organizations/organization-autocomplete')
+    )
 
     class Meta:
         model = Subsidy
diff --git a/forums/forms.py b/forums/forms.py
index f9cbb48e9..02a44678f 100644
--- a/forums/forms.py
+++ b/forums/forms.py
@@ -5,8 +5,10 @@ __license__ = "AGPL v3"
 from django import forms
 
 from ajax_select.fields import AutoCompleteSelectField
+from dal import autocomplete
 
 from .models import Forum, Meeting, Post, Motion
+from organizations.models import Organization
 
 
 class ForumForm(forms.ModelForm):
@@ -45,7 +47,10 @@ class ForumGroupPermissionsForm(forms.ModelForm):
 
 
 class ForumOrganizationPermissionsForm(forms.Form):
-    organization = AutoCompleteSelectField('organization_lookup')
+    organization = forms..ModelChoiceField(
+        queryset=Organization.objects.all(),
+        widget=autocomplete.ModelSelect2(url='/organizations/organization-autocomplete')
+    )
     can_view = forms.BooleanField()
     can_post = forms.BooleanField()
 
diff --git a/funders/forms.py b/funders/forms.py
index 728cacd87..a11f15698 100644
--- a/funders/forms.py
+++ b/funders/forms.py
@@ -7,9 +7,11 @@ from django import forms
 from .models import Funder, Grant
 
 from ajax_select.fields import AutoCompleteSelectField
+from dal import autocomplete
 
 from scipost.forms import HttpRefererFormMixin
 from scipost.models import Contributor
+from organizations.models import Organization
 
 
 class FunderRegistrySearchForm(forms.Form):
@@ -27,7 +29,10 @@ class FunderSelectForm(forms.Form):
 
 
 class FunderOrganizationSelectForm(forms.ModelForm):
-    organization = AutoCompleteSelectField('organization_lookup')
+    organization = forms..ModelChoiceField(
+        queryset=Organization.objects.all(),
+        widget=autocomplete.ModelSelect2(url='/organizations/organization-autocomplete')
+    )
 
     class Meta:
         model = Funder
diff --git a/journals/forms.py b/journals/forms.py
index 7dbd24d12..d90072a49 100644
--- a/journals/forms.py
+++ b/journals/forms.py
@@ -16,7 +16,8 @@ from django.forms import BaseModelFormSet, modelformset_factory
 from django.template import loader
 from django.utils import timezone
 
-from ajax_select.fields import AutoCompleteSelectField
+#from ajax_select.fields import AutoCompleteSelectField
+from dal import autocomplete
 
 from .constants import STATUS_DRAFT, STATUS_PUBLICLY_OPEN,\
     PUBLICATION_PREPUBLISHED, PUBLICATION_PUBLISHED
@@ -31,6 +32,7 @@ from .signals import notify_manuscript_published
 from funders.models import Grant, Funder
 from journals.models import Journal
 from mails.utils import DirectMailUtil
+from organizations.models import Organization
 from production.constants import PROOFS_PUBLISHED
 from production.models import ProductionEvent
 from production.signals import notify_stream_status_change
@@ -120,7 +122,11 @@ PublicationAuthorOrderingFormSet = modelformset_factory(
 
 
 class AuthorsTableOrganizationSelectForm(forms.ModelForm):
-    organization = AutoCompleteSelectField('organization_lookup')
+    # organization = AutoCompleteSelectField('organization_lookup')
+    organization = forms..ModelChoiceField(
+        queryset=Organization.objects.all(),
+        widget=autocomplete.ModelSelect2(url='/organizations/organization-autocomplete')
+    )
 
     class Meta:
         model = PublicationAuthorsTable
diff --git a/organizations/templatetags/lookup.py b/organizations/templatetags/lookup.py
deleted file mode 100644
index a57ad364a..000000000
--- a/organizations/templatetags/lookup.py
+++ /dev/null
@@ -1,33 +0,0 @@
-__copyright__ = "Copyright © Stichting SciPost (SciPost Foundation)"
-__license__ = "AGPL v3"
-
-
-from django.core.exceptions import PermissionDenied
-from django.db.models import Q
-
-from ajax_select import register, LookupChannel
-
-from ..models import Organization
-
-
-@register('organization_lookup')
-class OrganizationLookup(LookupChannel):
-    model = Organization
-
-    def get_query(self, q, request):
-        return (self.model.objects.order_by('name')
-                .filter(Q(name__icontains=q) |
-                        Q(acronym__icontains=q) |
-                        Q(name_original__icontains=q))[:10])
-
-    def format_item_display(self, item):
-        """(HTML) format item for displaying item in the selected deck area."""
-        return u"<span class='auto_lookup_display'>%s</span>" % item.full_name_with_acronym
-
-    def format_match(self, item):
-        """(HTML) Format item for displaying in the dropdown."""
-        return item.full_name_with_acronym
-
-    def check_auth(self, request):
-        """Allow use by everybody (this is used in the registration form)."""
-        pass
diff --git a/organizations/urls.py b/organizations/urls.py
index 1f3afc104..fd4666aab 100644
--- a/organizations/urls.py
+++ b/organizations/urls.py
@@ -3,12 +3,18 @@ __license__ = "AGPL v3"
 
 
 from django.conf.urls import url
+from django.urls import path
 
 from . import views
 
 app_name = 'organizations'
 
 urlpatterns = [
+    path(
+        'organization-autocomplete/',
+        views.OrganizationAutocompleteView.as_view(),
+        name='organization-autocomplete',
+        ),
     url(
         r'^$',
         views.OrganizationListView.as_view(),
diff --git a/organizations/views.py b/organizations/views.py
index 5ec12cd69..762be18a4 100644
--- a/organizations/views.py
+++ b/organizations/views.py
@@ -8,6 +8,7 @@ from django.contrib.auth.mixins import UserPassesTestMixin
 from django.core.exceptions import PermissionDenied
 from django.urls import reverse_lazy
 from django.db import transaction
+from django.db.models import Q
 from django.shortcuts import get_object_or_404, render, redirect
 from django.urls import reverse
 from django.utils import timezone
@@ -15,6 +16,7 @@ from django.views.generic.detail import DetailView
 from django.views.generic.edit import CreateView, UpdateView, DeleteView
 from django.views.generic.list import ListView
 
+from dal import autocomplete
 from guardian.decorators import permission_required
 
 from .constants import ORGTYPE_PRIVATE_BENEFACTOR,\
@@ -27,10 +29,27 @@ from funders.models import Funder
 from mails.utils import DirectMailUtil
 from mails.views import MailEditorSubview
 from organizations.decorators import has_contact
+from organizations.models import Organization
 
 from scipost.mixins import PermissionsMixin, PaginationMixin
 
 
+######################
+# Autocomplete views #
+######################
+
+class OrganizationAutocompleteView(autocomplete.Select2QuerySetView):
+    """To feed the Select2 widget."""
+    def get_queryset(self):
+        qs = Organization.objects.all()
+        if self.q:
+            qs = qs.filter(
+                Q(name__icontains=self.q) |
+                Q(name_original__icontains=self.q) |
+                Q(acronym__icontains=self.q))
+        return qs
+
+
 class OrganizationCreateView(PermissionsMixin, CreateView):
     """
     Create a new Organization.
diff --git a/profiles/forms.py b/profiles/forms.py
index e5ed8296d..03c1841c9 100644
--- a/profiles/forms.py
+++ b/profiles/forms.py
@@ -5,9 +5,11 @@ __license__ = "AGPL v3"
 from django import forms
 
 from ajax_select.fields import AutoCompleteSelectField
+from dal import autocomplete
 
 from common.forms import ModelChoiceFieldwithid
 from invitations.models import RegistrationInvitation
+from organizations.models import Organization
 from scipost.models import Contributor
 from submissions.models import RefereeInvitation
 
@@ -179,7 +181,11 @@ class ProfileSelectForm(forms.Form):
 
 
 class AffiliationForm(forms.ModelForm):
-    organization = AutoCompleteSelectField('organization_lookup')
+    # organization = AutoCompleteSelectField('organization_lookup')
+    organization = forms..ModelChoiceField(
+        queryset=Organization.objects.all(),
+        widget=autocomplete.ModelSelect2(url='/organizations/organization-autocomplete')
+    )
 
     class Meta:
         model = Affiliation
diff --git a/scipost/forms.py b/scipost/forms.py
index 1761b7f75..fa0f0b12e 100644
--- a/scipost/forms.py
+++ b/scipost/forms.py
@@ -19,6 +19,7 @@ from django_countries import countries
 from django_countries.widgets import CountrySelectWidget
 
 from ajax_select.fields import AutoCompleteSelectField
+from dal import autocomplete
 from haystack.forms import ModelSearchForm as HayStackSearchForm
 
 from .behaviors import orcid_validator
@@ -41,6 +42,7 @@ from funders.models import Grant
 from invitations.models import CitationNotification
 from journals.models import PublicationAuthorsTable, Publication
 from mails.utils import DirectMailUtil
+from organizations.models import Organization
 from profiles.models import Profile, ProfileEmail, Affiliation
 from submissions.models import Submission, EditorialAssignment, RefereeInvitation, Report, \
     EditorialCommunication, EICRecommendation
@@ -95,14 +97,23 @@ class RegistrationForm(forms.Form):
         widget=forms.TextInput({
             'placeholder': 'Recommended. Get one at orcid.org'}))
     discipline = forms.ChoiceField(choices=SCIPOST_DISCIPLINES, label='* Main discipline')
-    current_affiliation = AutoCompleteSelectField(
-        'organization_lookup',
+    current_affiliation = forms.ModelChoiceField(
+        queryset=Organization.objects.all(),
+        widget=autocomplete.ModelSelect2(url='/organizations/organization-autocomplete'),
+        label='* Current affiliation',
         help_text=('Start typing, then select in the popup; '
                    'if you do not find the organization you seek, '
                    'please fill in your institution name and address instead.'),
-        show_help_text=False,
-        required=False,
-        label='* Current affiliation')
+        required=False
+    )
+    # current_affiliation = AutoCompleteSelectField(
+    #     'organization_lookup',
+    #     help_text=('Start typing, then select in the popup; '
+    #                'if you do not find the organization you seek, '
+    #                'please fill in your institution name and address instead.'),
+    #     show_help_text=False,
+    #     required=False,
+    #     label='* Current affiliation')
     address = forms.CharField(
         label='Institution name and address', max_length=1000,
         widget=forms.TextInput({'placeholder': '[only if you did not find your affiliation above]'}),
-- 
GitLab