Skip to content

Commit

Permalink
Merge pull request #18 from arthur-schnitzler/main
Browse files Browse the repository at this point in the history
autocomplete uses id instead of uri
  • Loading branch information
csae8092 authored Jan 3, 2024
2 parents 2fb7da1 + c85f7d2 commit f25b5ca
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 98 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,4 @@ media/listperson.xml
media/pmb-log.csv
media/listorg.xml
media/listbibl.xml
staticfiles/
94 changes: 5 additions & 89 deletions apis_core/apis_entities/autocomplete3.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,12 @@
import re
from functools import reduce

import dateutil.parser
import requests
from dal import autocomplete
from django import http
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import FieldError
from django.db.models import Q

from apis_core.apis_metainfo.models import Collection, Uri
from apis_core.apis_vocabularies.models import VocabsBaseClass

from .models import AbstractEntity
Expand Down Expand Up @@ -77,45 +73,13 @@ def get_more(self):


class GenericEntitiesAutocomplete(autocomplete.Select2ListView):
@staticmethod
def parse_stanbol_object(obj, key, *args):
if len(args) > 0:
lst1 = args[0]
else:
lst1 = None
if obj[1] == "GNDDate":
if lst1 is not None:
try:
return dateutil.parser.parse(lst1[key][0]["value"])
except:
return lst1[key][0]["value"]
else:
return obj[0]
elif obj[1] == "String":
if lst1 is not None:
return lst1[key][0]["value"]
else:
return obj[0]
elif obj[1] == "gndLong":
if lst1 is not None:
try:
return re.search(
"Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)", lst1[key][0]["value"]
).group(1)
except:
print("extract fails")
return None
else:
print("no match")

def get(self, request, *args, **kwargs):
page_size = 20
offset = (int(self.request.GET.get("page", 1)) - 1) * page_size
ac_type = self.kwargs["entity"]
db_include = self.kwargs.get("db_include", False)
ent_merge_pk = self.kwargs.get("ent_merge_pk", False)
choices = []
headers = {"Content-Type": "application/json"}
ent_model = AbstractEntity.get_entity_class_of_name(ac_type)
if not self.q:
q3 = False
Expand Down Expand Up @@ -163,27 +127,18 @@ def get(self, request, *args, **kwargs):
res = []
test_db = True
test_stanbol = False
test_stanbol_list = dict()
more = True
if not db_include:
for r in res[offset : offset + page_size]:
for r in res[offset: offset + page_size]:
if int(r.pk) == int(ent_merge_pk):
continue

f = dict()
dataclass = ""
try:
f["id"] = Uri.objects.filter(
entity=r, uri__contains=f"/entity/{r.id}"
)[0].uri
f["id"] = r.id
except:
continue
if hasattr(r, "lng"):
if r.lng and r.lat:
dataclass = 'data-vis-tooltip="{}" data-lat="{}" \
data-long="{}" class="apis-autocomplete-span"'.format(
ac_type, r.lat, r.lng
)
f[
"text"
] = "<span {}><small>db</small> <b>{}</b> <small>db-ID: {}</small> </span> ".format(
Expand Down Expand Up @@ -230,66 +185,27 @@ def get(self, request, *args, **kwargs):
{"id": x.pk, "text": x.label}
for x in vocab_model.objects.filter(name__icontains=q).order_by(
"parent_class__name", "name"
)[offset : offset + page_size]
)[offset: offset + page_size]
]
else:
choices = [
{"id": x.pk, "text": x.label}
for x in vocab_model.objects.filter(
Q(name__icontains=q) | Q(name_reverse__icontains=q)
).order_by("parent_class__name", "name")[
offset : offset + page_size
offset: offset + page_size
]
]
elif direct == "reverse":
choices = [
{"id": x.pk, "text": x.label_reverse}
for x in vocab_model.objects.filter(
Q(name__icontains=q) | Q(name_reverse__icontains=q)
).order_by("parent_class__name", "name")[offset : offset + page_size]
).order_by("parent_class__name", "name")[offset: offset + page_size]
]
if len(choices) == page_size:
more = True
return http.HttpResponse(
json.dumps({"results": choices + [], "pagination": {"more": more}}),
content_type="application/json",
)


class GenericNetworkEntitiesAutocomplete(autocomplete.Select2ListView):
def get(self, request, *args, **kwargs):
page_size = 20
offset = (int(self.request.GET.get("page", 1)) - 1) * page_size
more = False
entity = self.kwargs["entity"]
q = self.q
if q.startswith("cl:"):
res = Collection.objects.filter(name__icontains=q[3:])
results = [{"id": "cl:" + str(x.pk), "text": x.name} for x in res]
else:
ent_model = ContentType.objects.get(
app_label__startswith="apis_", model=entity
).model_class()
try:
arg_list = [
Q(**{x + "__icontains": q})
for x in settings.APIS_ENTITIES[entity.title()]["search"]
]
except KeyError:
arg_list = [Q(**{x + "__icontains": q}) for x in ["name"]]
try:
res = ent_model.objects.filter(
reduce(operator.or_, arg_list)
).distinct()[offset : offset + page_size]
except FieldError:
arg_list = [Q(**{x + "__icontains": q}) for x in ["text"]]
res = ent_model.objects.filter(
reduce(operator.or_, arg_list)
).distinct()[offset : offset + page_size]
results = [{"id": x.pk, "text": str(x)} for x in res]
if len(results) == page_size:
more = True
return http.HttpResponse(
json.dumps({"results": results, "pagination": {"more": more}}),
content_type="application/json",
)
3 changes: 1 addition & 2 deletions apis_core/apis_entities/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,13 @@ def test_009_merge_view(self):
before = Person.objects.all().count()
source = Person.objects.all().first()
target = Person.objects.all().last()
target_uri = target.uri_set.all().first()
form_kwargs = {"entity": "person"}
form_kwargs["ent_merge_pk"] = source.id
url = reverse(
"apis:apis_entities:merge_view",
kwargs={"entity": "person", "ent_merge_pk": source.id},
)
response = client.post(url, {"entity": target_uri})
response = client.post(url, {"entity": target.id})
self.assertEqual(response.status_code, 302)
after = Person.objects.all().count()
self.assertTrue(before > after)
Expand Down
11 changes: 4 additions & 7 deletions apis_core/apis_entities/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import importlib

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
Expand All @@ -14,9 +13,8 @@
from django.views.generic import DeleteView
from django_tables2 import RequestConfig

from apis_core.apis_entities.models import AbstractEntity
from apis_core.apis_entities.models import AbstractEntity, TempEntityClass
from apis_core.apis_labels.models import Label
from apis_core.apis_metainfo.models import Uri
from apis_core.apis_relations.models import AbstractRelation
from apis_core.apis_relations.tables import LabelTableEdit, get_generic_relations_table

Expand Down Expand Up @@ -97,7 +95,7 @@ def post(self, request, *args, **kwargs):
form = get_entities_form(entity.title())
form = form(request.POST, instance=instance)
if form.is_valid():
entity_2 = form.save()
form.save()
return redirect(
reverse(
"apis:apis_entities:generic_entities_edit_view",
Expand Down Expand Up @@ -194,10 +192,9 @@ def post(self, request, *args, **kwargs):
ent_merge_pk = kwargs.get("ent_merge_pk", False)
form = MergeForm(entity, request.POST, ent_merge_pk=ent_merge_pk)
if form.is_valid():
uri = form.data["entity"]
target_id = form.data["entity"]
if ent_merge_pk:
uri_obj = Uri.objects.get(uri=uri)
target = uri_obj.entity
target = TempEntityClass.objects.get(id=target_id)
entity_model_class = ContentType.objects.get(
app_label="apis_entities", model__iexact=entity
).model_class()
Expand Down

0 comments on commit f25b5ca

Please sign in to comment.