-{% endblock %}
\ No newline at end of file
diff --git a/apis_core/apis_entities/templates/apis_entities/place_create.html b/apis_core/apis_entities/templates/apis_entities/place_create.html
index 058de27..fdeb7a8 100644
--- a/apis_core/apis_entities/templates/apis_entities/place_create.html
+++ b/apis_core/apis_entities/templates/apis_entities/place_create.html
@@ -92,7 +92,7 @@
-{% endblock %}
\ No newline at end of file
diff --git a/apis_core/apis_entities/templatetags/apis_templatetags.py b/apis_core/apis_entities/templatetags/apis_templatetags.py
index 9e6cd1e..9287a16 100644
--- a/apis_core/apis_entities/templatetags/apis_templatetags.py
+++ b/apis_core/apis_entities/templatetags/apis_templatetags.py
@@ -1,8 +1,9 @@
from django import template
+
register = template.Library()
-@register.inclusion_tag('apis_entities/apis_create_entities.html', takes_context=True)
+@register.inclusion_tag("apis_entities/apis_create_entities.html", takes_context=True)
def apis_create_entities(context):
values = {}
return values
diff --git a/apis_core/apis_entities/test_models.py b/apis_core/apis_entities/test_models.py
index 32e5c60..e7d1185 100644
--- a/apis_core/apis_entities/test_models.py
+++ b/apis_core/apis_entities/test_models.py
@@ -121,8 +121,15 @@ def test_merge_entities(self):
def test_merge_entities_no_selfself(self):
p1 = Person.objects.first()
- self.assertRaises(ValueError, p1.merge_with, [p1,])
-
+ self.assertRaises(
+ ValueError,
+ p1.merge_with,
+ [
+ p1,
+ ],
+ )
+
+
"""
def test_object_reversion(self):
with reversion.create_revision():
@@ -209,4 +216,3 @@ def test_perm_removed(self):
)
print(f"permissions revoked, patch: {res.status_code}")
self.assertEqual(res.status_code, 403)
-
\ No newline at end of file
diff --git a/apis_core/apis_entities/test_parsers.py b/apis_core/apis_entities/test_parsers.py
index 5dcfc5a..de13a4b 100644
--- a/apis_core/apis_entities/test_parsers.py
+++ b/apis_core/apis_entities/test_parsers.py
@@ -7,15 +7,33 @@
class RDFPlaceParserNewTestCase(TestCase):
-
def test_parse_place(self):
- plc = [("https://www.geonames.org/6951114/bad-zell.html", "Bad Zell", 48.34906, "https://sws.geonames.org/2782113/", "https://www.geonames.org/ontology#P.PPL"),
- ("https://sws.geonames.org/2779275/", "Freistadt", 48.51103, "https://sws.geonames.org/2782113/", "https://www.geonames.org/ontology#P.PPL"),
- ("https://sws.geonames.org/2761369", "Vienna", 48.20849, "https://sws.geonames.org/2782113/", "https://www.geonames.org/ontology#P.PPLC")
- ]
+ plc = [
+ (
+ "https://www.geonames.org/6951114/bad-zell.html",
+ "Bad Zell",
+ 48.34906,
+ "https://sws.geonames.org/2782113/",
+ "https://www.geonames.org/ontology#P.PPL",
+ ),
+ (
+ "https://sws.geonames.org/2779275/",
+ "Freistadt",
+ 48.51103,
+ "https://sws.geonames.org/2782113/",
+ "https://www.geonames.org/ontology#P.PPL",
+ ),
+ (
+ "https://sws.geonames.org/2761369",
+ "Vienna",
+ 48.20849,
+ "https://sws.geonames.org/2782113/",
+ "https://www.geonames.org/ontology#P.PPLC",
+ ),
+ ]
for p in plc:
print(p)
- o = RDFParser(p[0], 'Place')
+ o = RDFParser(p[0], "Place")
o.create_objct()
o2 = o.save()
print(type(o2.lat))
@@ -23,72 +41,89 @@ def test_parse_place(self):
self.assertEqual(o2.name, p[1])
self.assertEqual(o2.kind.name, p[4])
-
-
- #def test_parse_person(self):
- # o = RDFParser('http://d-nb.info/gnd/118650130', 'Person', uri_check=False)
- # o.create_objct()
- # print(o._foreign_keys)
- #print(o.objct)
- # print(o._attributes)
- # print(o.objct.name)
- # print(o._foreign_keys)
- # self.assertEqual(o.objct.name, 'Aristoteles')
- # o2 = o.save()
- # print(o2)
- # o3 = RDFParser('http://d-nb.info/gnd/118566512', 'Person', uri_check=False)
- # o3.create_objct()
- # print(o3._foreign_keys)
- # print(o3.objct)
- # print(o3._attributes)
- # print(f"name: {o3.objct.name}, {o3.objct.first_name}")
- # print(o3._foreign_keys)
- # self.assertEqual(o3.objct.name, 'Kreisky')
- # self.assertEqual(o3.objct.start_date_written, '1911-01-22')
- # o4 = o3.save()
- # print(o4)
- # print(o4.profession.all())
- # print(o4.start_date)
+ # def test_parse_person(self):
+ # o = RDFParser('http://d-nb.info/gnd/118650130', 'Person', uri_check=False)
+ # o.create_objct()
+ # print(o._foreign_keys)
+ # print(o.objct)
+ # print(o._attributes)
+ # print(o.objct.name)
+ # print(o._foreign_keys)
+ # self.assertEqual(o.objct.name, 'Aristoteles')
+ # o2 = o.save()
+ # print(o2)
+ # o3 = RDFParser('http://d-nb.info/gnd/118566512', 'Person', uri_check=False)
+ # o3.create_objct()
+ # print(o3._foreign_keys)
+ # print(o3.objct)
+ # print(o3._attributes)
+ # print(f"name: {o3.objct.name}, {o3.objct.first_name}")
+ # print(o3._foreign_keys)
+ # self.assertEqual(o3.objct.name, 'Kreisky')
+ # self.assertEqual(o3.objct.start_date_written, '1911-01-22')
+ # o4 = o3.save()
+ # print(o4)
+ # print(o4.profession.all())
+ # print(o4.start_date)
def test_merge(self):
- o = RDFParser('https://d-nb.info/gnd/118566512', 'Person', uri_check=False)
+ o = RDFParser("https://d-nb.info/gnd/118566512", "Person", uri_check=False)
o.create_objct()
o.save()
- o2 = RDFParser('https://d-nb.info/gnd/170686299', 'Person', uri_check=False).get_or_create()
+ o2 = RDFParser(
+ "https://d-nb.info/gnd/170686299", "Person", uri_check=False
+ ).get_or_create()
o.merge(o2)
print(o.objct.uri_set.all())
def test_place_of_birth(self):
- o = RDFParser('https://d-nb.info/gnd/118566512', 'Person', uri_check=False)
+ o = RDFParser("https://d-nb.info/gnd/118566512", "Person", uri_check=False)
o.create_objct()
o.save()
for p in PersonPlace.objects.all():
- print(p.related_place.name, p.related_place.uri_set.all(), p.related_place.lat)
+ print(
+ p.related_place.name, p.related_place.uri_set.all(), p.related_place.lat
+ )
def test_institution(self):
- o = RDFParser('https://d-nb.info/gnd/1001454-8', 'Institution', uri_check=False)
+ o = RDFParser("https://d-nb.info/gnd/1001454-8", "Institution", uri_check=False)
o.create_objct()
o2 = o.save()
print(o2.pk, o2.start_date, o2.start_date_written)
print(InstitutionPlace.objects.filter(related_institution_id=o2.pk))
- print(o2.label_set.all().values_list('label'))
-
+ print(o2.label_set.all().values_list("label"))
+
def test_use_uri_twice(self):
- self.assertRaises(ValueError, RDFParser, "https://www.geonames.org/6951114/bad-zell.html", "Place")
+ self.assertRaises(
+ ValueError,
+ RDFParser,
+ "https://www.geonames.org/6951114/bad-zell.html",
+ "Place",
+ )
def test_uri_twice_later(self):
- o = RDFParser('https://sws.geonames.org/2778843', 'Place', preserve_uri_minutes=0.5)
- self.assertRaises(ValueError, RDFParser, 'https://sws.geonames.org/2778843', "Place", preserve_uri_minutes=0.5)
+ o = RDFParser(
+ "https://sws.geonames.org/2778843", "Place", preserve_uri_minutes=0.5
+ )
+ self.assertRaises(
+ ValueError,
+ RDFParser,
+ "https://sws.geonames.org/2778843",
+ "Place",
+ preserve_uri_minutes=0.5,
+ )
time.sleep(35)
- o2 = RDFParser('https://sws.geonames.org/2778843', 'Place', preserve_uri_minutes=0.5).get_or_create()
+ o2 = RDFParser(
+ "https://sws.geonames.org/2778843", "Place", preserve_uri_minutes=0.5
+ ).get_or_create()
def test_institution_government(self):
- o = RDFParser('https://d-nb.info/gnd/2029534-0', 'Institution').get_or_create()
- self.assertEqual(o.name, 'Österreich. Bundesregierung')
- #self.assertEqual(o.start_date_written, '1945')
+ o = RDFParser("https://d-nb.info/gnd/2029534-0", "Institution").get_or_create()
+ self.assertEqual(o.name, "Österreich. Bundesregierung")
+ # self.assertEqual(o.start_date_written, '1945')
def test_uni_koeln(self):
- o = RDFParser('https://d-nb.info/gnd/2024231-1', 'Institution')
+ o = RDFParser("https://d-nb.info/gnd/2024231-1", "Institution")
o.create_objct()
print(o._foreign_keys)
o2 = o.save()
diff --git a/apis_core/apis_entities/urls.py b/apis_core/apis_entities/urls.py
index dc6685e..776a5a5 100644
--- a/apis_core/apis_entities/urls.py
+++ b/apis_core/apis_entities/urls.py
@@ -7,6 +7,11 @@
)
from .views2 import GenericEntitiesCreateStanbolView
+from .list_view_person import PersonListView
+from .list_view_work import WorkListView
+from .list_view_place import PlaceListView
+from .list_view_institution import InstitutionListView
+from .list_view_event import EventListView
app_name = "apis_entities"
@@ -31,6 +36,31 @@
views2.GenericEntitiesDeleteView.as_view(),
name="generic_entities_delete_view",
),
+ path(
+ "entity/person/list/",
+ PersonListView.as_view(),
+ name="person_list_view",
+ ),
+ path(
+ "entity/place/list/",
+ PlaceListView.as_view(),
+ name="place_list_view",
+ ),
+ path(
+ "entity/work/list/",
+ WorkListView.as_view(),
+ name="work_list_view",
+ ),
+ path(
+ "entity/institution/list/",
+ InstitutionListView.as_view(),
+ name="institution_list_view",
+ ),
+ path(
+ "entity/event/list/",
+ EventListView.as_view(),
+ name="event_list_view",
+ ),
path(
"entity//list/",
views.GenericListViewNew.as_view(),
@@ -42,12 +72,12 @@
name="generic_entities_stanbol_create",
),
path(
- "autocomplete/createstanbol//(?P[0-9]+)/",
+ "autocomplete/createstanbol///",
GenericEntitiesCreateStanbolView.as_view(),
name="generic_entities_stanbol_create",
),
path(
- "autocomplete//(?P[0-9]+)/",
+ "autocomplete///",
GenericEntitiesAutocomplete.as_view(),
name="generic_entities_autocomplete",
),
@@ -57,7 +87,7 @@
name="generic_entities_autocomplete",
),
path(
- "autocomplete//(?P[a-z]+)/",
+ "autocomplete///",
GenericEntitiesAutocomplete.as_view(),
name="generic_entities_autocomplete",
),
@@ -73,7 +103,7 @@
path("place/geojson/list/", views.getGeoJsonList, name="getGeoJsonList"),
path("place/network/list/", views.getNetJsonList, name="getNetJsonList"),
path(
- "resolve/place//(?P.+)",
+ "resolve/place//",
views.resolve_ambigue_place,
name="resolve_ambigue_place",
),
diff --git a/apis_core/apis_entities/views.py b/apis_core/apis_entities/views.py
index b748025..059ef6b 100644
--- a/apis_core/apis_entities/views.py
+++ b/apis_core/apis_entities/views.py
@@ -22,6 +22,8 @@
access_for_all_function,
ENTITIES_DEFAULT_COLS,
)
+
+from browsing.browsing_utils import GenericListView
from .filters import get_list_filter_of_entity
from .forms import (
GenericFilterFormHelper,
@@ -32,14 +34,6 @@
from .models import Place
from .tables import get_entities_table
-if "apis_highlighter" in settings.INSTALLED_APPS:
- from apis_highlighter.forms import SelectAnnotationProject
- from apis_highlighter.highlighter import highlight_text_new
-
-if "charts" in settings.INSTALLED_APPS:
- from charts.models import ChartConfig
- from charts.views import create_payload
-
###########################################################################
############################################################################
#
@@ -113,10 +107,7 @@ class GenericListViewNew(UserPassesTestMixin, ExportMixin, SingleTableView):
formhelper_class = GenericFilterFormHelper
context_filter_name = "filter"
paginate_by = 25
- template_name = getattr(
- settings, "APIS_LIST_VIEW_TEMPLATE", "apis:apis_entities/generic_list.html"
- )
- #login_url = "/accounts/login/"
+ template_name = "browsing/generic_list.html"
def get_model(self):
model = ContentType.objects.get(
@@ -156,7 +147,7 @@ def get_table(self, **kwargs):
if "table_fields" in settings.APIS_ENTITIES[entity.title()]:
default_cols = settings.APIS_ENTITIES[entity.title()]["table_fields"]
else:
- default_cols = ["name"]
+ default_cols = ["id", "name"]
default_cols = default_cols + selected_cols
self.table_class = get_entities_table(
self.entity.title(), edit_v, default_cols=default_cols
@@ -172,17 +163,10 @@ def get_context_data(self, **kwargs):
context = super(GenericListViewNew, self).get_context_data()
context[self.context_filter_name] = self.filter
context["entity"] = self.entity
+ print(f"#############{self.entity}")
context["app_name"] = "apis_entities"
entity = self.entity.title()
context["entity_create_stanbol"] = GenericEntitiesStanbolForm(self.entity)
- if "browsing" in settings.INSTALLED_APPS:
- from browsing.models import BrowsConf
-
- context["conf_items"] = list(
- BrowsConf.objects.filter(model_name=self.entity).values_list(
- "field_path", "label"
- )
- )
context["docstring"] = "{}".format(model.__doc__)
if model._meta.verbose_name_plural:
context["class_name"] = "{}".format(model._meta.verbose_name.title())
@@ -191,44 +175,15 @@ def get_context_data(self, **kwargs):
context["class_name"] = "{}".format(model.__name__)
else:
context["class_name"] = "{}s".format(model.__name__)
- try:
- context["get_arche_dump"] = model.get_arche_dump()
- except AttributeError:
- context["get_arche_dump"] = None
- try:
- context["create_view_link"] = model.get_createview_url()
- except AttributeError:
- context["create_view_link"] = None
- if "charts" in settings.INSTALLED_APPS:
- app_label = model._meta.app_label
- filtered_objs = ChartConfig.objects.filter(
- model_name=model.__name__.lower(), app_name=app_label
- )
- context["vis_list"] = filtered_objs
- context["property_name"] = self.request.GET.get("property")
- context["charttype"] = self.request.GET.get("charttype")
- if context["charttype"] and context["property_name"]:
- qs = self.get_queryset()
- chartdata = create_payload(
- context["entity"],
- context["property_name"],
- context["charttype"],
- qs,
- app_label=app_label,
- )
- context = dict(context, **chartdata)
- try:
- context["enable_merge"] = settings.APIS_ENTITIES[entity.title()]["merge"]
- except KeyError:
- context["enable_merge"] = False
+ context["create_view_link"] = None
+ context["enable_merge"] = False
try:
togg_cols = settings.APIS_ENTITIES[entity.title()]["additional_cols"]
except KeyError:
togg_cols = []
- if context["enable_merge"] and self.request.user.is_authenticated:
- togg_cols = togg_cols + ["merge"]
- context["togglable_colums"] = togg_cols + ENTITIES_DEFAULT_COLS
-
+ context["togglable_colums"] = {
+ x: x for x in [togg_cols + ENTITIES_DEFAULT_COLS][0]
+ }
return context
def render_to_response(self, context, **kwargs):
@@ -595,19 +550,3 @@ def generic_network_viz(request):
"apis:apis_entities/generic_network_visualization.html",
{"form": form},
)
-
-
-############################################################################
-############################################################################
-#
-# Reversion Views
-#
-############################################################################
-############################################################################
-# TODO: add again as soon as the module has been bumped to new django version
-# class ReversionCompareView(HistoryCompareDetailView):
-# template_name = 'apis_entities/compare_base.html'
-
-# def dispatch(self, request, app, kind, pk, *args, **kwargs):
-# self.model = ContentType.objects.get(app_label=app, model=kind).model_class()
-# return super(ReversionCompareView, self).dispatch(request, *args, **kwargs)
diff --git a/apis_core/apis_entities/views2.py b/apis_core/apis_entities/views2.py
index 9dd44da..af710b3 100644
--- a/apis_core/apis_entities/views2.py
+++ b/apis_core/apis_entities/views2.py
@@ -36,8 +36,8 @@ def get(self, request, *args, **kwargs):
side_bar = []
for rel in relations:
match = [
- rel.get_related_entity_classA().__name__.lower(),
- rel.get_related_entity_classB().__name__.lower(),
+ rel.get_related_entity_classa().__name__.lower(),
+ rel.get_related_entity_classb().__name__.lower(),
]
prefix = "{}{}-".format(match[0].title()[:2], match[1].title()[:2])
table = get_generic_relations_table(
@@ -46,8 +46,8 @@ def get(self, request, *args, **kwargs):
title_card = ""
if match[0] == match[1]:
title_card = entity.title()
- dict_1 = {"related_" + entity.lower() + "A": instance}
- dict_2 = {"related_" + entity.lower() + "B": instance}
+ dict_1 = {"related_" + entity.lower() + "a": instance}
+ dict_2 = {"related_" + entity.lower() + "b": instance}
objects = rel.objects.filter(Q(**dict_1) | Q(**dict_2))
else:
if match[0].lower() == entity.lower():
diff --git a/apis_core/apis_labels/admin.py b/apis_core/apis_labels/admin.py
index 52264d3..919eb16 100644
--- a/apis_core/apis_labels/admin.py
+++ b/apis_core/apis_labels/admin.py
@@ -7,14 +7,18 @@
# Register your models here.
class BaseAdmin(admin.ModelAdmin):
-
- search_fields = ('label',)
+
+ search_fields = ("label",)
list_filter = (
- "isoCode_639_3",
+ "isocode_639_3",
"label_type",
)
- list_display = ('label', 'temp_entity', )
- exclude = ('temp_entity', )
+ list_display = (
+ "label",
+ "temp_entity",
+ )
+ exclude = ("temp_entity",)
actions = [csvexport]
-admin.site.register(Label, BaseAdmin)
\ No newline at end of file
+
+admin.site.register(Label, BaseAdmin)
diff --git a/apis_core/apis_labels/forms.py b/apis_core/apis_labels/forms.py
index a3a57f7..4701426 100644
--- a/apis_core/apis_labels/forms.py
+++ b/apis_core/apis_labels/forms.py
@@ -10,15 +10,12 @@
# This class LabelForm here is only refered to in apis_labels/views.py which would be loaded by the respective urls in apis_labels/urls.py
# However none of these urls seem to work when called in the browser
class LabelForm(forms.ModelForm):
- isoCode = forms.CharField(
- required=True,
- label="ISO 639-3"
- )
+ isoCode = forms.CharField(required=True, label="ISO 639-3")
label = forms.CharField(required=True, help_text="The entities label or name.")
class Meta:
model = Label
- fields = ['label', 'isoCode_639_3', 'label_type']
+ fields = ["label", "isocode_639_3", "label_type"]
def __init__(self, *args, **kwargs):
super(LabelForm, self).__init__(*args, **kwargs)
diff --git a/apis_core/apis_labels/migrations/0001_initial.py b/apis_core/apis_labels/migrations/0001_initial.py
index ec5538d..fcd4feb 100644
--- a/apis_core/apis_labels/migrations/0001_initial.py
+++ b/apis_core/apis_labels/migrations/0001_initial.py
@@ -7,16 +7,40 @@ class Migration(migrations.Migration):
initial = True
- dependencies = [
- ]
+ dependencies = []
operations = [
migrations.CreateModel(
- name='Label',
+ name="Label",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('label', models.CharField(blank=True, help_text='The entities label or name.', max_length=255)),
- ('isoCode_639_3', models.CharField(blank=True, default='deu', help_text="The ISO 639-3 (or 2) code for the label's language.", max_length=3, null=True, verbose_name='ISO Code')),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "label",
+ models.CharField(
+ blank=True,
+ help_text="The entities label or name.",
+ max_length=255,
+ ),
+ ),
+ (
+ "isocode_639_3",
+ models.CharField(
+ blank=True,
+ default="deu",
+ help_text="The ISO 639-3 (or 2) code for the label's language.",
+ max_length=3,
+ null=True,
+ verbose_name="ISO Code",
+ ),
+ ),
],
),
]
diff --git a/apis_core/apis_labels/migrations/0002_auto_20200121_1227.py b/apis_core/apis_labels/migrations/0002_auto_20200121_1227.py
index 5148894..c52ab60 100644
--- a/apis_core/apis_labels/migrations/0002_auto_20200121_1227.py
+++ b/apis_core/apis_labels/migrations/0002_auto_20200121_1227.py
@@ -9,20 +9,28 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ('apis_vocabularies', '0001_initial'),
- ('apis_labels', '0001_initial'),
- ('apis_metainfo', '0001_initial'),
+ ("apis_vocabularies", "0001_initial"),
+ ("apis_labels", "0001_initial"),
+ ("apis_metainfo", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='label',
- name='label_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='apis_vocabularies.LabelType'),
+ model_name="label",
+ name="label_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="apis_vocabularies.LabelType",
+ ),
),
migrations.AddField(
- model_name='label',
- name='temp_entity',
- field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='apis_metainfo.TempEntityClass'),
+ model_name="label",
+ name="temp_entity",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="apis_metainfo.TempEntityClass",
+ ),
),
]
diff --git a/apis_core/apis_labels/migrations/0003_auto_20200221_1731.py b/apis_core/apis_labels/migrations/0003_auto_20200221_1731.py
index f297b51..90073ac 100644
--- a/apis_core/apis_labels/migrations/0003_auto_20200221_1731.py
+++ b/apis_core/apis_labels/migrations/0003_auto_20200221_1731.py
@@ -6,48 +6,52 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_labels', '0002_auto_20200121_1227'),
+ ("apis_labels", "0002_auto_20200121_1227"),
]
operations = [
migrations.AddField(
- model_name='label',
- name='end_date',
+ model_name="label",
+ name="end_date",
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
- model_name='label',
- name='end_date_written',
- field=models.CharField(blank=True, max_length=255, null=True, verbose_name='End'),
+ model_name="label",
+ name="end_date_written",
+ field=models.CharField(
+ blank=True, max_length=255, null=True, verbose_name="End"
+ ),
),
migrations.AddField(
- model_name='label',
- name='end_end_date',
+ model_name="label",
+ name="end_end_date",
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
- model_name='label',
- name='end_start_date',
+ model_name="label",
+ name="end_start_date",
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
- model_name='label',
- name='start_date',
+ model_name="label",
+ name="start_date",
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
- model_name='label',
- name='start_date_written',
- field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Start'),
+ model_name="label",
+ name="start_date_written",
+ field=models.CharField(
+ blank=True, max_length=255, null=True, verbose_name="Start"
+ ),
),
migrations.AddField(
- model_name='label',
- name='start_end_date',
+ model_name="label",
+ name="start_end_date",
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
- model_name='label',
- name='start_start_date',
+ model_name="label",
+ name="start_start_date",
field=models.DateField(blank=True, null=True),
),
]
diff --git a/apis_core/apis_labels/models.py b/apis_core/apis_labels/models.py
index a11bcef..6fb0ebe 100644
--- a/apis_core/apis_labels/models.py
+++ b/apis_core/apis_labels/models.py
@@ -10,13 +10,19 @@
class Label(models.Model):
label = models.CharField(
- max_length=255, blank=True, help_text="The entities label or name.")
- isoCode_639_3 = models.CharField(
- max_length=3, blank=True, null=True,
+ max_length=255, blank=True, help_text="The entities label or name."
+ )
+ isocode_639_3 = models.CharField(
+ max_length=3,
+ blank=True,
+ null=True,
help_text="The ISO 639-3 (or 2) code for the label's language.",
- verbose_name='ISO Code', default='deu')
- label_type = models.ForeignKey(LabelType, blank=True, null=True,
- on_delete=models.SET_NULL)
+ verbose_name="ISO Code",
+ default="deu",
+ )
+ label_type = models.ForeignKey(
+ LabelType, blank=True, null=True, on_delete=models.SET_NULL
+ )
start_date = models.DateField(blank=True, null=True)
start_start_date = models.DateField(blank=True, null=True)
@@ -38,19 +44,24 @@ class Label(models.Model):
)
# TODO __sresch__ add related_name="label_set" here to be consistent with other usages throughout django
- temp_entity = models.ForeignKey("apis_metainfo.TempEntityClass", on_delete=models.CASCADE)
+ temp_entity = models.ForeignKey(
+ "apis_metainfo.TempEntityClass", on_delete=models.CASCADE
+ )
def get_web_object(self):
result = {
- 'relation_pk': self.pk,
- 'label': self.label,
- 'isoCode_639_3': self.isoCode_639_3,
- 'label_type': self.label_type.name}
+ "relation_pk": self.pk,
+ "label": self.label,
+ "isocode_639_3": self.isocode_639_3,
+ "label_type": self.label_type.name,
+ }
return result
def save(self, *args, **kwargs):
- if self.label != unicodedata.normalize('NFC', self.label): #secure correct unicode encoding
- self.label = unicodedata.normalize('NFC', self.label)
+ if self.label != unicodedata.normalize(
+ "NFC", self.label
+ ): # secure correct unicode encoding
+ self.label = unicodedata.normalize("NFC", self.label)
def parse_dates():
@@ -65,14 +76,16 @@ def parse_dates():
if self.start_date_written:
# If some textual user input of a start date is there, then parse it
- start_date, start_start_date, start_end_date = \
- DateParser.parse_date(self.start_date_written)
+ start_date, start_start_date, start_end_date = DateParser.parse_date(
+ self.start_date_written
+ )
if self.end_date_written:
# If some textual user input of an end date is there, then parse it
- end_date, end_start_date, end_end_date = \
- DateParser.parse_date(self.end_date_written)
+ end_date, end_start_date, end_end_date = DateParser.parse_date(
+ self.end_date_written
+ )
self.start_date = start_date
self.start_start_date = start_start_date
diff --git a/apis_core/apis_labels/serializers.py b/apis_core/apis_labels/serializers.py
index 86eebde..a314c0a 100644
--- a/apis_core/apis_labels/serializers.py
+++ b/apis_core/apis_labels/serializers.py
@@ -9,4 +9,4 @@ class LabelSerializerLegacy(serializers.ModelSerializer):
class Meta:
model = Label
- fields = ('id', 'label', 'isoCode_639_3', 'label_type')
+ fields = ("id", "label", "isocode_639_3", "label_type")
diff --git a/apis_core/apis_labels/views.py b/apis_core/apis_labels/views.py
index 4519043..d68118a 100644
--- a/apis_core/apis_labels/views.py
+++ b/apis_core/apis_labels/views.py
@@ -8,42 +8,50 @@
class LabelListView(generic.ListView):
- model = Label
- template_name = 'apis_labels/labels_list.html'
- context_object_name = 'object_list'
+ model = Label
+ template_name = "apis_labels/labels_list.html"
+ context_object_name = "object_list"
- def get_queryset(self):
- return Label.objects.order_by('label')
+ def get_queryset(self):
+ return Label.objects.order_by("label")
def label_create(request):
- if request.method == "POST":
- form = LabelForm(request.POST)
- if form.is_valid():
- form.save()
- return redirect('apis_labels:label_list')
- else:
- return render (request, 'apis_labels/label_create.html', {'form':form})
- else:
- form = LabelForm()
- return render (request, 'apis_labels/label_create.html', {'form':form})
+ if request.method == "POST":
+ form = LabelForm(request.POST)
+ if form.is_valid():
+ form.save()
+ return redirect("apis_labels:label_list")
+ else:
+ return render(request, "apis_labels/label_create.html", {"form": form})
+ else:
+ form = LabelForm()
+ return render(request, "apis_labels/label_create.html", {"form": form})
def label_edit(request, pk):
- instance = get_object_or_404(Label, pk=pk)
- if request.method == "POST":
- form = LabelForm(request.POST, instance=instance)
- if form.is_valid():
- form.save()
- return redirect('apis_labels:label_list')
- else:
- return render (request, 'apis_labels/label_create.html', {'form':form,'instance':instance})
- else:
- form = LabelForm(instance=instance)
- return render(request, 'apis_labels/label_create.html', {'form':form, 'instance':instance})
+ instance = get_object_or_404(Label, pk=pk)
+ if request.method == "POST":
+ form = LabelForm(request.POST, instance=instance)
+ if form.is_valid():
+ form.save()
+ return redirect("apis_labels:label_list")
+ else:
+ return render(
+ request,
+ "apis_labels/label_create.html",
+ {"form": form, "instance": instance},
+ )
+ else:
+ form = LabelForm(instance=instance)
+ return render(
+ request,
+ "apis_labels/label_create.html",
+ {"form": form, "instance": instance},
+ )
class LabelDelete(DeleteView):
- model = Label
- template_name = 'apis_templates/confirm_delete.html'
- success_url = reverse_lazy('apis_labels:label_list')
+ model = Label
+ template_name = "apis_templates/confirm_delete.html"
+ success_url = reverse_lazy("apis_labels:label_list")
diff --git a/apis_core/apis_metainfo/admin.py b/apis_core/apis_metainfo/admin.py
index d41986c..729662e 100644
--- a/apis_core/apis_metainfo/admin.py
+++ b/apis_core/apis_metainfo/admin.py
@@ -6,6 +6,3 @@
admin.site.register(Collection)
admin.site.register(Text)
admin.site.register(Uri)
-
-
-
diff --git a/apis_core/apis_metainfo/api_renderers.py b/apis_core/apis_metainfo/api_renderers.py
index b70d22d..cbf25f7 100644
--- a/apis_core/apis_metainfo/api_renderers.py
+++ b/apis_core/apis_metainfo/api_renderers.py
@@ -3,11 +3,13 @@
class TEIBaseRenderer(renderers.BaseRenderer):
- media_type = 'application/xml+tei'
- format = 'xml'
+ media_type = "application/xml+tei"
+ format = "xml"
def render(self, data, media_type=None, renderer_context=None):
- data = render_to_string("apis_metainfo/TEI_renderer.xml", {'data': data, 'renderer_context': renderer_context})
+ data = render_to_string(
+ "apis_metainfo/TEI_renderer.xml",
+ {"data": data, "renderer_context": renderer_context},
+ )
return data
-
diff --git a/apis_core/apis_metainfo/api_views.py b/apis_core/apis_metainfo/api_views.py
index aa33ee0..8ecfde5 100644
--- a/apis_core/apis_metainfo/api_views.py
+++ b/apis_core/apis_metainfo/api_views.py
@@ -2,8 +2,12 @@
from .models import Collection, Text, Source, Uri, TempEntityClass
from .serializers import (
- CollectionSerializer, TextSerializer, SourceSerializer,
- UriSerializer, TempEntityClassSerializer)
+ CollectionSerializer,
+ TextSerializer,
+ SourceSerializer,
+ UriSerializer,
+ TempEntityClassSerializer,
+)
class CollectionViewSet(viewsets.ModelViewSet):
diff --git a/apis_core/apis_metainfo/filters.py b/apis_core/apis_metainfo/filters.py
deleted file mode 100644
index 35a8f1d..0000000
--- a/apis_core/apis_metainfo/filters.py
+++ /dev/null
@@ -1,26 +0,0 @@
-import django_filters
-
-from .models import *
-
-
-class UriListFilter(django_filters.FilterSet):
-
- uri = django_filters.CharFilter(
- lookup_expr='icontains',
- help_text=Uri._meta.get_field('uri').help_text,
- label=Uri._meta.get_field('uri').verbose_name
- )
- domain = django_filters.CharFilter(
- lookup_expr='icontains',
- help_text=Uri._meta.get_field('domain').help_text,
- label=Uri._meta.get_field('domain').verbose_name
- )
- entity__name = django_filters.CharFilter(
- lookup_expr='icontains',
- help_text=Uri._meta.get_field('entity').help_text,
- label=Uri._meta.get_field('entity').verbose_name
- )
-
- class Meta:
- model = Uri
- fields = "__all__"
diff --git a/apis_core/apis_metainfo/forms.py b/apis_core/apis_metainfo/forms.py
index a237694..1211d49 100644
--- a/apis_core/apis_metainfo/forms.py
+++ b/apis_core/apis_metainfo/forms.py
@@ -1,6 +1,5 @@
-from crispy_forms.bootstrap import Accordion, AccordionGroup
from crispy_forms.helper import FormHelper
-from crispy_forms.layout import Submit, Layout
+from crispy_forms.layout import Submit
from dal import autocomplete
from django import forms
@@ -12,36 +11,18 @@ class Meta:
model = Uri
fields = "__all__"
widgets = {
- 'entity': autocomplete.ModelSelect2(
- url='apis_core:apis_metainfo-ac:apis_tempentity-autocomplete'),
- }
+ "entity": autocomplete.ModelSelect2(
+ url="apis_core:apis_metainfo-ac:apis_tempentity-autocomplete"
+ ),
+ }
def __init__(self, *args, **kwargs):
super(UriForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = True
- self.helper.form_class = 'form-horizontal'
- self.helper.label_class = 'col-md-3'
- self.helper.field_class = 'col-md-9'
- self.helper.add_input(Submit('submit', 'save'),)
-
-
-class UriFilterFormHelper(FormHelper):
- def __init__(self, *args, **kwargs):
- super(UriFilterFormHelper, self).__init__(*args, **kwargs)
- self.helper = FormHelper()
- self.form_class = 'genericFilterForm'
- self.form_method = 'GET'
- self.helper.form_tag = False
- self.add_input(Submit('Filter', 'Search'))
- self.layout = Layout(
- Accordion(
- AccordionGroup(
- 'Filter',
- 'uri',
- 'domain',
- 'entity__name',
- css_id="basic_search_fields"
- ),
- )
- )
+ self.helper.form_class = "form-horizontal"
+ self.helper.label_class = "col-md-3"
+ self.helper.field_class = "col-md-9"
+ self.helper.add_input(
+ Submit("submit", "save"),
+ )
diff --git a/apis_core/apis_metainfo/migrations/0001_initial.py b/apis_core/apis_metainfo/migrations/0001_initial.py
index 221e817..436f268 100644
--- a/apis_core/apis_metainfo/migrations/0001_initial.py
+++ b/apis_core/apis_metainfo/migrations/0001_initial.py
@@ -8,75 +8,157 @@ class Migration(migrations.Migration):
initial = True
- dependencies = [
- ]
+ dependencies = []
operations = [
migrations.CreateModel(
- name='Collection',
+ name="Collection",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('name', models.CharField(max_length=255)),
- ('description', models.TextField(blank=True)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("description", models.TextField(blank=True)),
],
),
migrations.CreateModel(
- name='Source',
+ name="Source",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('orig_filename', models.CharField(blank=True, max_length=255)),
- ('indexed', models.BooleanField(default=False)),
- ('pubinfo', models.CharField(blank=True, max_length=400)),
- ('author', models.CharField(blank=True, max_length=255)),
- ('orig_id', models.PositiveIntegerField(blank=True, null=True)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("orig_filename", models.CharField(blank=True, max_length=255)),
+ ("indexed", models.BooleanField(default=False)),
+ ("pubinfo", models.CharField(blank=True, max_length=400)),
+ ("author", models.CharField(blank=True, max_length=255)),
+ ("orig_id", models.PositiveIntegerField(blank=True, null=True)),
],
),
migrations.CreateModel(
- name='TempEntityClass',
+ name="TempEntityClass",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('name', models.CharField(blank=True, max_length=255)),
- ('review', models.BooleanField(default=False, help_text='Should be set to True, if the data record holds up quality standards.')),
- ('start_date', models.DateField(blank=True, null=True)),
- ('start_start_date', models.DateField(blank=True, null=True)),
- ('start_end_date', models.DateField(blank=True, null=True)),
- ('end_date', models.DateField(blank=True, null=True)),
- ('end_start_date', models.DateField(blank=True, null=True)),
- ('end_end_date', models.DateField(blank=True, null=True)),
- ('start_date_written', models.CharField(blank=True, max_length=255, null=True, verbose_name='Start')),
- ('end_date_written', models.CharField(blank=True, max_length=255, null=True, verbose_name='End')),
- ('status', models.CharField(max_length=100)),
- ('references', models.TextField(blank=True, null=True)),
- ('notes', models.TextField(blank=True, null=True)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=255)),
+ (
+ "review",
+ models.BooleanField(
+ default=False,
+ help_text="Should be set to True, if the data record holds up quality standards.",
+ ),
+ ),
+ ("start_date", models.DateField(blank=True, null=True)),
+ ("start_start_date", models.DateField(blank=True, null=True)),
+ ("start_end_date", models.DateField(blank=True, null=True)),
+ ("end_date", models.DateField(blank=True, null=True)),
+ ("end_start_date", models.DateField(blank=True, null=True)),
+ ("end_end_date", models.DateField(blank=True, null=True)),
+ (
+ "start_date_written",
+ models.CharField(
+ blank=True, max_length=255, null=True, verbose_name="Start"
+ ),
+ ),
+ (
+ "end_date_written",
+ models.CharField(
+ blank=True, max_length=255, null=True, verbose_name="End"
+ ),
+ ),
+ ("status", models.CharField(max_length=100)),
+ ("references", models.TextField(blank=True, null=True)),
+ ("notes", models.TextField(blank=True, null=True)),
],
),
migrations.CreateModel(
- name='Text',
+ name="Text",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('text', models.TextField(blank=True)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("text", models.TextField(blank=True)),
],
),
migrations.CreateModel(
- name='Uri',
+ name="Uri",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('uri', models.URLField(blank=True, max_length=255, null=True, unique=True)),
- ('domain', models.CharField(blank=True, max_length=255)),
- ('rdf_link', models.URLField(blank=True)),
- ('loaded', models.BooleanField(default=False)),
- ('loaded_time', models.DateTimeField(blank=True, null=True)),
- ('entity', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='apis_metainfo.TempEntityClass')),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "uri",
+ models.URLField(blank=True, max_length=255, null=True, unique=True),
+ ),
+ ("domain", models.CharField(blank=True, max_length=255)),
+ ("rdf_link", models.URLField(blank=True)),
+ ("loaded", models.BooleanField(default=False)),
+ ("loaded_time", models.DateTimeField(blank=True, null=True)),
+ (
+ "entity",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
),
migrations.CreateModel(
- name='UriCandidate',
+ name="UriCandidate",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('uri', models.URLField()),
- ('confidence', models.FloatField(blank=True, null=True)),
- ('responsible', models.CharField(max_length=255)),
- ('entity', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='apis_metainfo.TempEntityClass')),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("uri", models.URLField()),
+ ("confidence", models.FloatField(blank=True, null=True)),
+ ("responsible", models.CharField(max_length=255)),
+ (
+ "entity",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
),
]
diff --git a/apis_core/apis_metainfo/migrations/0002_auto_20200121_1227.py b/apis_core/apis_metainfo/migrations/0002_auto_20200121_1227.py
index 44c295d..b91dc40 100644
--- a/apis_core/apis_metainfo/migrations/0002_auto_20200121_1227.py
+++ b/apis_core/apis_metainfo/migrations/0002_auto_20200121_1227.py
@@ -9,50 +9,75 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ('apis_vocabularies', '0001_initial'),
- ('auth', '0009_alter_user_last_name_max_length'),
- ('apis_metainfo', '0001_initial'),
+ ("apis_vocabularies", "0001_initial"),
+ ("auth", "0009_alter_user_last_name_max_length"),
+ ("apis_metainfo", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='text',
- name='kind',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='apis_vocabularies.TextType'),
+ model_name="text",
+ name="kind",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="apis_vocabularies.TextType",
+ ),
),
migrations.AddField(
- model_name='text',
- name='source',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='apis_metainfo.Source'),
+ model_name="text",
+ name="source",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="apis_metainfo.Source",
+ ),
),
migrations.AddField(
- model_name='tempentityclass',
- name='collection',
- field=models.ManyToManyField(to='apis_metainfo.Collection'),
+ model_name="tempentityclass",
+ name="collection",
+ field=models.ManyToManyField(to="apis_metainfo.Collection"),
),
migrations.AddField(
- model_name='tempentityclass',
- name='source',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='apis_metainfo.Source'),
+ model_name="tempentityclass",
+ name="source",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="apis_metainfo.Source",
+ ),
),
migrations.AddField(
- model_name='tempentityclass',
- name='text',
- field=models.ManyToManyField(blank=True, to='apis_metainfo.Text'),
+ model_name="tempentityclass",
+ name="text",
+ field=models.ManyToManyField(blank=True, to="apis_metainfo.Text"),
),
migrations.AddField(
- model_name='collection',
- name='collection_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='apis_vocabularies.CollectionType'),
+ model_name="collection",
+ name="collection_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="apis_vocabularies.CollectionType",
+ ),
),
migrations.AddField(
- model_name='collection',
- name='groups_allowed',
- field=models.ManyToManyField(to='auth.Group'),
+ model_name="collection",
+ name="groups_allowed",
+ field=models.ManyToManyField(to="auth.Group"),
),
migrations.AddField(
- model_name='collection',
- name='parent_class',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='apis_metainfo.Collection'),
+ model_name="collection",
+ name="parent_class",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="apis_metainfo.Collection",
+ ),
),
]
diff --git a/apis_core/apis_metainfo/migrations/0003_tempentityclass_published.py b/apis_core/apis_metainfo/migrations/0003_tempentityclass_published.py
index a1f31e5..9fd4716 100644
--- a/apis_core/apis_metainfo/migrations/0003_tempentityclass_published.py
+++ b/apis_core/apis_metainfo/migrations/0003_tempentityclass_published.py
@@ -6,13 +6,13 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_metainfo', '0002_auto_20200121_1227'),
+ ("apis_metainfo", "0002_auto_20200121_1227"),
]
operations = [
migrations.AddField(
- model_name='tempentityclass',
- name='published',
+ model_name="tempentityclass",
+ name="published",
field=models.BooleanField(default=False),
),
]
diff --git a/apis_core/apis_metainfo/migrations/0004_collection_published.py b/apis_core/apis_metainfo/migrations/0004_collection_published.py
index 01e1ae9..f2c4539 100644
--- a/apis_core/apis_metainfo/migrations/0004_collection_published.py
+++ b/apis_core/apis_metainfo/migrations/0004_collection_published.py
@@ -6,13 +6,13 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_metainfo', '0003_tempentityclass_published'),
+ ("apis_metainfo", "0003_tempentityclass_published"),
]
operations = [
migrations.AddField(
- model_name='collection',
- name='published',
+ model_name="collection",
+ name="published",
field=models.BooleanField(default=False),
),
]
diff --git a/apis_core/apis_metainfo/migrations/0005_text_lang.py b/apis_core/apis_metainfo/migrations/0005_text_lang.py
index 20b1e66..a8029b7 100644
--- a/apis_core/apis_metainfo/migrations/0005_text_lang.py
+++ b/apis_core/apis_metainfo/migrations/0005_text_lang.py
@@ -6,13 +6,20 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_metainfo', '0004_collection_published'),
+ ("apis_metainfo", "0004_collection_published"),
]
operations = [
migrations.AddField(
- model_name='text',
- name='lang',
- field=models.CharField(blank=True, default='deu', help_text="The ISO 639-3 (or 2) code for the label's language.", max_length=3, null=True, verbose_name='ISO Code'),
+ model_name="text",
+ name="lang",
+ field=models.CharField(
+ blank=True,
+ default="deu",
+ help_text="The ISO 639-3 (or 2) code for the label's language.",
+ max_length=3,
+ null=True,
+ verbose_name="ISO Code",
+ ),
),
]
diff --git a/apis_core/apis_metainfo/migrations/0006_remove_text_lang.py b/apis_core/apis_metainfo/migrations/0006_remove_text_lang.py
index 9b81bee..de89033 100644
--- a/apis_core/apis_metainfo/migrations/0006_remove_text_lang.py
+++ b/apis_core/apis_metainfo/migrations/0006_remove_text_lang.py
@@ -6,12 +6,12 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_metainfo', '0005_text_lang'),
+ ("apis_metainfo", "0005_text_lang"),
]
operations = [
migrations.RemoveField(
- model_name='text',
- name='lang',
+ model_name="text",
+ name="lang",
),
]
diff --git a/apis_core/apis_metainfo/models.py b/apis_core/apis_metainfo/models.py
index f8abd7d..7c82ef6 100644
--- a/apis_core/apis_metainfo/models.py
+++ b/apis_core/apis_metainfo/models.py
@@ -11,13 +11,14 @@
from django.db.models.query import QuerySet
from django.urls import reverse
from django.utils.functional import cached_property
-# from model_utils.managers import InheritanceManager
+from model_utils.managers import InheritanceManager
from apis_core.apis_entities.serializers_generic import EntitySerializer
from apis_core.apis_labels.models import Label
from apis_core.apis_vocabularies.models import CollectionType, LabelType, TextType
from django.contrib.contenttypes.fields import GenericRelation
+
# from helper_functions.highlighter import highlight_text
from apis_core.default_settings.NER_settings import autocomp_settings
from apis_core.helper_functions import DateParser
@@ -68,8 +69,7 @@ class TempEntityClass(models.Model):
notes = models.TextField(blank=True, null=True)
published = models.BooleanField(default=False)
objects = models.Manager()
- # objects_inheritance = InheritanceManager()
-
+ objects_inheritance = InheritanceManager()
def __str__(self):
if self.name != "" and hasattr(
@@ -85,7 +85,6 @@ def save(self, parse_dates=True, *args, **kwargs):
"""Adaption of the save() method of the class to automatically parse string-dates into date objects"""
if parse_dates:
-
# overwrite every field with None as default
start_date = None
start_start_date = None
@@ -257,7 +256,6 @@ def merge_with(self, entities):
rels = ContentType.objects.filter(
app_label="apis_relations", model__icontains=e_a
)
- print(entities)
for ent in entities:
e_b = type(ent).__name__
e_b_pk = ent.pk
@@ -310,7 +308,7 @@ def get_serialization(self):
class Source(models.Model):
- """ Holds information about entities and their relations"""
+ """Holds information about entities and their relations"""
orig_filename = models.CharField(max_length=255, blank=True)
indexed = models.BooleanField(default=False)
@@ -326,7 +324,7 @@ def __str__(self):
class Collection(models.Model):
- """ Allows to group entities and relation. """
+ """Allows to group entities and relation."""
name = models.CharField(max_length=255)
description = models.TextField(blank=True)
@@ -372,13 +370,29 @@ def __str__(self):
return "ID: {}".format(self.id)
-
class Uri(models.Model):
- uri = models.URLField(blank=True, null=True, unique=True, max_length=255)
- domain = models.CharField(max_length=255, blank=True)
+ uri = models.URLField(
+ blank=True,
+ null=True,
+ unique=True,
+ max_length=255,
+ verbose_name="URI",
+ help_text="Eindeutiger Identifier",
+ )
+ domain = models.CharField(
+ max_length=255,
+ blank=True,
+ verbose_name="Domain",
+ help_text="Domain der Normdatenquelle, z.B. gnd, wikidata, geonames, ...",
+ )
rdf_link = models.URLField(blank=True)
entity = models.ForeignKey(
- TempEntityClass, blank=True, null=True, on_delete=models.CASCADE
+ TempEntityClass,
+ blank=True,
+ null=True,
+ on_delete=models.CASCADE,
+ verbose_name="Entität",
+ help_text="Entität die mit dieser URI verbunden ist",
)
# loaded set to True when RDF was loaded and parsed into the data model
loaded = models.BooleanField(default=False)
diff --git a/apis_core/apis_metainfo/serializers.py b/apis_core/apis_metainfo/serializers.py
index d1250d4..60bb103 100644
--- a/apis_core/apis_metainfo/serializers.py
+++ b/apis_core/apis_metainfo/serializers.py
@@ -9,7 +9,9 @@ class CollectionSerializer(serializers.HyperlinkedModelSerializer):
view_name="apis:apis_api:text-detail", lookup_field="pk"
)
collection_type = serializers.HyperlinkedRelatedField(
- view_name="apis:apis_api:collectiontype-detail", lookup_field="pk", read_only=True
+ view_name="apis:apis_api:collectiontype-detail",
+ lookup_field="pk",
+ read_only=True,
)
parent_class = serializers.HyperlinkedRelatedField(
view_name="apis:apis_api:collection-detail", lookup_field="pk", read_only=True
diff --git a/apis_core/apis_metainfo/tables.py b/apis_core/apis_metainfo/tables.py
index ee8cf15..2c1befe 100644
--- a/apis_core/apis_metainfo/tables.py
+++ b/apis_core/apis_metainfo/tables.py
@@ -1,9 +1,6 @@
-import django_tables2 as tables
from django.db.models import F
from django.utils.html import format_html
-from .models import Uri
-
# generic order_FOO methods for start_date_written and end_date_written to be used in all kinds of tables where a queryset is loaded
# whose model has start_date_written and end_date_written. These methods order the *_date_written by their corresponding
@@ -25,9 +22,12 @@
# In the case of e.g. start_date_written,
# the table class thus must have a method / class variable 'order_start_date_written = generic_order_start_date_written'
+
def generic_order_start_date_written(self, queryset, is_descending):
if is_descending:
- queryset = queryset.order_by(F("start_date").desc(nulls_last=True)) #nulls_last=True puts null values behind non-null values
+ queryset = queryset.order_by(
+ F("start_date").desc(nulls_last=True)
+ ) # nulls_last=True puts null values behind non-null values
else:
queryset = queryset.order_by(F("start_date").asc(nulls_last=True))
@@ -43,7 +43,6 @@ def generic_order_end_date_written(self, queryset, is_descending):
return (queryset, True)
-
def helper_render_date(value, var_date, var_start_date, var_end_date):
"""
helper function to avoid duplicated code. It checks the various sub-dates of a model's date field for them being None
@@ -59,7 +58,6 @@ def helper_render_date(value, var_date, var_start_date, var_end_date):
:return: html string : which has the value of the written date and the parsed dates as mouse overlay helptext
"""
-
# Various if-else branches checking which of the date fields are not None and should be used
if var_start_date != None and var_end_date != None:
@@ -82,37 +80,18 @@ def helper_render_date(value, var_date, var_start_date, var_end_date):
def generic_render_start_date_written(self, record, value):
return helper_render_date(
- value = value,
- var_date = record.start_date,
- var_start_date = record.start_start_date,
- var_end_date = record.start_end_date
+ value=value,
+ var_date=record.start_date,
+ var_start_date=record.start_start_date,
+ var_end_date=record.start_end_date,
)
def generic_render_end_date_written(self, record, value):
return helper_render_date(
- value = value,
- var_date = record.end_date,
- var_start_date = record.end_start_date,
- var_end_date = record.end_end_date
+ value=value,
+ var_date=record.end_date,
+ var_start_date=record.end_start_date,
+ var_end_date=record.end_end_date,
)
-
-
-
-
-class UriTable(tables.Table):
- id = tables.LinkColumn()
- entity = tables.TemplateColumn(
- "{{ record.entity }}",
- orderable=True, verbose_name="related Entity"
- )
- ent_type = tables.TemplateColumn(
- "{{ record.entity.get_child_class }}",
- orderable=False, verbose_name="Entity Type"
- )
-
- class Meta:
- model = Uri
- sequence = ('id', 'uri')
- attrs = {"class": "table table-responsive table-hover"}
diff --git a/apis_core/apis_metainfo/urls.py b/apis_core/apis_metainfo/urls.py
index d91c1f0..da2e366 100644
--- a/apis_core/apis_metainfo/urls.py
+++ b/apis_core/apis_metainfo/urls.py
@@ -1,11 +1,12 @@
from django.urls import path
from . import views
+from apis_core.apis_entities.list_view_uris import UriListView
app_name = "apis_metainfo"
urlpatterns = [
- path("apis/metainfo/uri/", views.UriListView.as_view(), name="uri_browse"),
+ path("apis/metainfo/uri/", UriListView.as_view(), name="uri_browse"),
path("uri/detail/", views.UriDetailView.as_view(), name="uri_detail"),
path("uri/create/", views.UriCreate.as_view(), name="uri_create"),
path("uri/edit/", views.UriUpdate.as_view(), name="uri_edit"),
diff --git a/apis_core/apis_metainfo/validators.py b/apis_core/apis_metainfo/validators.py
index d1bea29..aa91644 100644
--- a/apis_core/apis_metainfo/validators.py
+++ b/apis_core/apis_metainfo/validators.py
@@ -5,9 +5,11 @@
from django.core.validators import RegexValidator
# TODO __sresch__ : remove once sure
-date_validator = RegexValidator(regex=re.compile(r'^([0-9]{1,2}\.[0-9]{1,2}\.)?[0-9]{4}$'),
- message="Please enter a valide date: (DD).(MM).YYYY",
- code='invalide_date')
+date_validator = RegexValidator(
+ regex=re.compile(r"^([0-9]{1,2}\.[0-9]{1,2}\.)?[0-9]{4}$"),
+ message="Please enter a valide date: (DD).(MM).YYYY",
+ code="invalide_date",
+)
# date_validator2 = RegexValidator(regex=re.compile(r'^([0-9]{1,2}\.[0-9]{1,2}\.)?[0-9]{4}$'),
# message="Please enter a valide date: (DD)-(MM)-YYYY.",
-# code='invalide_date') still needed?
\ No newline at end of file
+# code='invalide_date') still needed?
diff --git a/apis_core/apis_metainfo/views.py b/apis_core/apis_metainfo/views.py
index 839e828..5cb5d3b 100644
--- a/apis_core/apis_metainfo/views.py
+++ b/apis_core/apis_metainfo/views.py
@@ -6,11 +6,9 @@
from django.views.generic.detail import DetailView
from django.views.generic.edit import DeleteView
-from browsing.browsing_utils import GenericListView, BaseCreateView, BaseUpdateView
-from .filters import UriListFilter
-from .forms import UriFilterFormHelper, UriForm
+from browsing.browsing_utils import BaseCreateView, BaseUpdateView
+from .forms import UriForm
from .models import Uri
-from .tables import UriTable
PROJECT_NAME = settings.PROJECT_NAME
@@ -19,28 +17,18 @@
def beacon(request):
domain = request.build_absolute_uri("/")
result = f"#FORMAT: BEACON\n#NAME: {PROJECT_NAME}\n"
- uris = [(x.uri, x.entity.name, x.entity.id) for x in Uri.objects.filter(uri__icontains='d-nb.info/gnd')]
+ uris = [
+ (x.uri, x.entity.name, x.entity.id)
+ for x in Uri.objects.filter(uri__icontains="d-nb.info/gnd")
+ ]
for x in uris:
- result = result + f"{x[0]}|"f"{x[1]}|"f"{domain}entity/{x[2]}/\n"
+ result = result + f"{x[0]}|" f"{x[1]}|" f"{domain}entity/{x[2]}/\n"
return HttpResponse(result, content_type="text/plain")
-class UriListView(GenericListView):
- model = Uri
- filter_class = UriListFilter
- formhelper_class = UriFilterFormHelper
- table_class = UriTable
- init_columns = [
- 'id',
- 'uri',
- 'entity',
- ]
- enable_merge = True
-
-
class UriDetailView(DetailView):
model = Uri
- template_name = 'apis_metainfo/uri_detail.html'
+ template_name = "apis_metainfo/uri_detail.html"
class UriCreate(BaseCreateView):
@@ -65,8 +53,8 @@ def dispatch(self, *args, **kwargs):
class UriDelete(DeleteView):
model = Uri
- template_name = 'webpage/confirm_delete.html'
- success_url = reverse_lazy('apis_core:apis_metainfo:uri_browse')
+ template_name = "webpage/confirm_delete.html"
+ success_url = reverse_lazy("apis_core:apis_metainfo:uri_browse")
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
diff --git a/apis_core/apis_relations/autocomplete_light_registry.py b/apis_core/apis_relations/autocomplete_light_registry.py
index 2b21865..3335ba2 100644
--- a/apis_core/apis_relations/autocomplete_light_registry.py
+++ b/apis_core/apis_relations/autocomplete_light_registry.py
@@ -16,16 +16,14 @@
class StanbolAutocompleteBase(al.AutocompleteListTemplate):
- autocomplete_template = 'apis_templates/autocomplete/stanbol.html'
+ autocomplete_template = "apis_templates/autocomplete/stanbol.html"
- widget_attrs = {
-
- }
+ widget_attrs = {}
attrs = {
- 'data-autocomplete-minimum-characters': 3,
- 'placeholder': u'Start typing to get suggestions',
- 'class': 'autocomplete-ort-uri form-control'
+ "data-autocomplete-minimum-characters": 3,
+ "placeholder": "Start typing to get suggestions",
+ "class": "autocomplete-ort-uri form-control",
}
@staticmethod
@@ -34,89 +32,89 @@ def parse_stanbol_object(obj, key, *args):
lst1 = args[0]
else:
lst1 = None
- if obj[1] == 'GNDDate':
+ if obj[1] == "GNDDate":
if lst1 is not None:
try:
- return dateutil.parser.parse(lst1[key][0]['value'])
+ return dateutil.parser.parse(lst1[key][0]["value"])
except:
- return lst1[key][0]['value']
+ return lst1[key][0]["value"]
else:
return obj[0]
- elif obj[1] == 'String':
+ elif obj[1] == "String":
if lst1 is not None:
- return lst1[key][0]['value']
+ return lst1[key][0]["value"]
else:
return obj[0]
- elif obj[1] == 'gndLong':
+ elif obj[1] == "gndLong":
if lst1 is not None:
try:
- return re.search('Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)', lst1[key][0]['value']).group(1)
+ return re.search(
+ "Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)", lst1[key][0]["value"]
+ ).group(1)
except:
- print('extract fails')
+ print("extract fails")
return None
else:
- print('no match')
+ print("no match")
def choices_for_request(self):
ac_type = self.autocomplete_type
ac_type_model = self.autocomplete_type_model
choices = []
- headers = {'Content-Type': 'application/json'}
- q = self.request.GET.get('q')
+ headers = {"Content-Type": "application/json"}
+ q = self.request.GET.get("q")
for m in ac_type_model:
arg_list = []
for mm in m[1]:
- arg_list.append(Q(**{mm+'__icontains': q}))
+ arg_list.append(Q(**{mm + "__icontains": q}))
res = m[0].objects.filter(reduce(operator.or_, arg_list)).distinct()
for r in res:
f = dict()
- f['ac_type'] = '_'.join(ac_type)
- f['name'] = r
- f['score'] = None
+ f["ac_type"] = "_".join(ac_type)
+ f["name"] = r
+ f["score"] = None
try:
- f['uri'] = Uri.objects.filter(entity=r)[0].uri
+ f["uri"] = Uri.objects.filter(entity=r)[0].uri
except:
continue
- f['source'] = 'db'
- if ac_type[0] == 'Place':
+ f["source"] = "db"
+ if ac_type[0] == "Place":
if r.lng != None and r.lat != None:
- f['long'] = str(r.lng)
- f['lat'] = str(r.lat)
- f['descr'] = m[2][0].format(*[getattr(r, s) for s in m[2][1]])
+ f["long"] = str(r.lng)
+ f["lat"] = str(r.lat)
+ f["descr"] = m[2][0].format(*[getattr(r, s) for s in m[2][1]])
choices.append(f)
for o in ac_type:
for y in ac_settings[o]:
ldpath = ""
- for d in y['fields'].keys():
- ldpath += "{} = <{}>;\n".format(d, y['fields'][d][0])
- data = {
- 'limit': 20,
- 'name': q,
- 'ldpath': ldpath
- }
+ for d in y["fields"].keys():
+ ldpath += "{} = <{}>;\n".format(d, y["fields"][d][0])
+ data = {"limit": 20, "name": q, "ldpath": ldpath}
try:
- r = requests.get(y['url'], params=data, headers=headers)
+ r = requests.get(y["url"], params=data, headers=headers)
if r.status_code != 200:
- choices.append({'name': 'Connection to Stanbol failed'})
+ choices.append({"name": "Connection to Stanbol failed"})
continue
res = r.json()
except:
- choices.append({'name': 'Connection to Stanbol failed'})
+ choices.append({"name": "Connection to Stanbol failed"})
continue
- for x in res['results']:
+ for x in res["results"]:
f = dict()
- name = x['name'][0]['value']
- score = str(x[ac_settings['score']][0]['value'])
- id = x[ac_settings['uri']]
- f['ac_type'] = '_'.join(ac_type)
- f['name'] = name
- f['score'] = score
- f['uri'] = id
- f['source'] = y['source']
- for field in y['fields'].keys():
+ name = x["name"][0]["value"]
+ score = str(x[ac_settings["score"]][0]["value"])
+ id = x[ac_settings["uri"]]
+ f["ac_type"] = "_".join(ac_type)
+ f["name"] = name
+ f["score"] = score
+ f["uri"] = id
+ f["source"] = y["source"]
+ for field in y["fields"].keys():
if field in x.keys():
- f[field] = self.parse_stanbol_object(y['fields'][field], field, x)
+ f[field] = self.parse_stanbol_object(
+ y["fields"][field], field, x
+ )
else:
f[field] = None
choices.append(f)
@@ -124,21 +122,19 @@ def choices_for_request(self):
class AddRelationBaseAutocomplete(al.AutocompleteListTemplate):
- autocomplete_template = 'apis_templates/autocomplete/AddRelation.html'
+ autocomplete_template = "apis_templates/autocomplete/AddRelation.html"
- widget_attrs = {
-
- }
+ widget_attrs = {}
attrs = {
- 'data-autocomplete-minimum-characters': 3,
- 'placeholder': u'Start typing to get suggestions',
- 'class': 'autocomplete-add-relation form-control'
+ "data-autocomplete-minimum-characters": 3,
+ "placeholder": "Start typing to get suggestions",
+ "class": "autocomplete-add-relation form-control",
}
def choices_for_request(self):
- q = self.request.GET.get('q', None)
- instance_pk = self.request.GET.get('instance_pk', None)
+ q = self.request.GET.get("q", None)
+ instance_pk = self.request.GET.get("instance_pk", None)
choices = []
model_name = self.model2.__name__.lower()
if instance_pk and q:
@@ -146,46 +142,98 @@ def choices_for_request(self):
else:
return choices
for rel in self.relations:
- if 'related_' + model_name in dir(rel):
- dd = rel.objects.filter(**{
- 'related_' + model_name: instance,
- 'relation_type__name__icontains': q}).exclude(annotation__isnull=False)
+ if "related_" + model_name in dir(rel):
+ dd = rel.objects.filter(
+ **{
+ "related_" + model_name: instance,
+ "relation_type__name__icontains": q,
+ }
+ ).exclude(annotation__isnull=False)
choices.extend(dd)
- elif 'related_' + model_name + 'A' in dir(rel):
+ elif "related_" + model_name + "A" in dir(rel):
choices.extend(
rel.objects.filter(
- Q(**{
- 'related_' + model_name + 'A': instance,
- 'relation_type__name__icontains': q}) |
- Q(**{
- 'related_' + model_name + 'B': instance,
- 'relation_type__name__icontains': q})).distinct().exclude(annotation__isnull=False))
+ Q(
+ **{
+ "related_" + model_name + "A": instance,
+ "relation_type__name__icontains": q,
+ }
+ )
+ | Q(
+ **{
+ "related_" + model_name + "B": instance,
+ "relation_type__name__icontains": q,
+ }
+ )
+ )
+ .distinct()
+ .exclude(annotation__isnull=False)
+ )
return choices
class PlaceAutocomplete(StanbolAutocompleteBase):
- autocomplete_type = ['Place', ]
- autocomplete_type_model = [(Place, ['name', 'label__label'], ('Status: {}', ['status'])), ]
+ autocomplete_type = [
+ "Place",
+ ]
+ autocomplete_type_model = [
+ (Place, ["name", "label__label"], ("Status: {}", ["status"])),
+ ]
class InstitutionAutocomplete(StanbolAutocompleteBase):
- autocomplete_type = ['Institution', ]
- autocomplete_type_model = [(Institution, ['name', 'label__label'], ('Status: {}, Gründungsdatum: {}', ['status', 'start_date_written'])), ]
+ autocomplete_type = [
+ "Institution",
+ ]
+ autocomplete_type_model = [
+ (
+ Institution,
+ ["name", "label__label"],
+ ("Status: {}, Gründungsdatum: {}", ["status", "start_date_written"]),
+ ),
+ ]
class PersonAutocomplete(StanbolAutocompleteBase):
- autocomplete_type = ['Person', ]
- autocomplete_type_model = [(Person, ['name', 'first_name', 'label__label'], ('Geburtsdatum: {}, Sterbedatum: {}', ['start_date_written', 'end_date_written']))]
+ autocomplete_type = [
+ "Person",
+ ]
+ autocomplete_type_model = [
+ (
+ Person,
+ ["name", "first_name", "label__label"],
+ (
+ "Geburtsdatum: {}, Sterbedatum: {}",
+ ["start_date_written", "end_date_written"],
+ ),
+ )
+ ]
class EventAutocomplete(StanbolAutocompleteBase):
- autocomplete_type = ['Event', ]
- autocomplete_type_model = [(Event, ['name', 'label__label'], ('Start date: {}, Status: {}', ['start_date', 'status'])), ]
+ autocomplete_type = [
+ "Event",
+ ]
+ autocomplete_type_model = [
+ (
+ Event,
+ ["name", "label__label"],
+ ("Start date: {}, Status: {}", ["start_date", "status"]),
+ ),
+ ]
class WorkAutocomplete(StanbolAutocompleteBase):
- autocomplete_type = ['Work', ]
- autocomplete_type_model = [(Work, ['name', 'label__label'], ('Start date: {}, Status: {}', ['start_date', 'status'])), ]
+ autocomplete_type = [
+ "Work",
+ ]
+ autocomplete_type_model = [
+ (
+ Work,
+ ["name", "label__label"],
+ ("Start date: {}, Status: {}", ["start_date", "status"]),
+ ),
+ ]
class AddRelationPersonHighlighterAutocomplete(AddRelationBaseAutocomplete):
diff --git a/apis_core/apis_relations/forms.py b/apis_core/apis_relations/forms.py
index 62a373e..f1899fd 100644
--- a/apis_core/apis_relations/forms.py
+++ b/apis_core/apis_relations/forms.py
@@ -14,21 +14,27 @@
# Generic
##############################################
-class EntityLabelForm(forms.ModelForm):
+class EntityLabelForm(forms.ModelForm):
class Meta:
model = Label
- fields = ['label', 'isoCode_639_3', 'label_type', 'start_date_written', 'end_date_written']
+ fields = [
+ "label",
+ "isocode_639_3",
+ "label_type",
+ "start_date_written",
+ "end_date_written",
+ ]
def save(self, site_instance, instance=None, commit=True):
cd = self.cleaned_data
if instance:
x = Label.objects.get(pk=instance)
- x.label = cd['label']
- x.isoCode_639_3 = cd['isoCode_639_3']
- x.label_type = cd['label_type']
- x.start_date_written = cd['start_date_written']
- x.end_date_written = cd['end_date_written']
+ x.label = cd["label"]
+ x.isocode_639_3 = cd["isocode_639_3"]
+ x.label_type = cd["label_type"]
+ x.start_date_written = cd["start_date_written"]
+ x.end_date_written = cd["end_date_written"]
else:
x = super(EntityLabelForm, self).save(commit=False)
x.temp_entity = site_instance
@@ -36,37 +42,46 @@ def save(self, site_instance, instance=None, commit=True):
return x
def __init__(self, siteID=None, *args, **kwargs):
- entity_type = kwargs.pop('entity_type', False)
- self.request = kwargs.pop('request', False)
+ entity_type = kwargs.pop("entity_type", False)
+ self.request = kwargs.pop("request", False)
super(EntityLabelForm, self).__init__(*args, **kwargs)
- self.fields['label'].required = True
- self.fields['label_type'].required = True
+ self.fields["label"].required = True
+ self.fields["label_type"].required = True
self.helper = FormHelper()
- self.helper.form_class = 'EntityLabelForm'
+ self.helper.form_class = "EntityLabelForm"
self.helper.form_tag = False
- instance = getattr(self, 'instance', None)
+ instance = getattr(self, "instance", None)
if instance != None:
if instance.start_date_written:
- self.fields['start_date_written'].help_text = DateParser.get_date_help_text_from_dates(
+ self.fields[
+ "start_date_written"
+ ].help_text = DateParser.get_date_help_text_from_dates(
single_date=instance.start_date,
single_start_date=instance.start_start_date,
single_end_date=instance.start_end_date,
single_date_written=instance.start_date_written,
)
else:
- self.fields['start_date_written'].help_text = DateParser.get_date_help_text_default()
+ self.fields[
+ "start_date_written"
+ ].help_text = DateParser.get_date_help_text_default()
if instance.end_date_written:
- self.fields['end_date_written'].help_text = DateParser.get_date_help_text_from_dates(
+ self.fields[
+ "end_date_written"
+ ].help_text = DateParser.get_date_help_text_from_dates(
single_date=instance.end_date,
single_start_date=instance.end_start_date,
single_end_date=instance.end_end_date,
single_date_written=instance.end_date_written,
)
else:
- self.fields['end_date_written'].help_text = DateParser.get_date_help_text_default()
+ self.fields[
+ "end_date_written"
+ ].help_text = DateParser.get_date_help_text_default()
+
##############################################
# Person
@@ -76,6 +91,7 @@ def __init__(self, siteID=None, *args, **kwargs):
class PersonLabelForm(EntityLabelForm):
pass
+
##############################################
# Institutions
##############################################
@@ -89,6 +105,7 @@ class InstitutionLabelForm(EntityLabelForm):
# Places
##############################################
+
class PlaceLabelForm(EntityLabelForm):
pass
@@ -113,7 +130,7 @@ class PlaceEntityForm(forms.Form):
def save(self, *args, **kwargs):
cd = self.cleaned_data
- pl = Place.get_or_create_uri(cd['place_uri'])
+ pl = Place.get_or_create_uri(cd["place_uri"])
if not pl:
- pl = RDFParser(cd['place_uri'], 'Place').get_or_create()
+ pl = RDFParser(cd["place_uri"], "Place").get_or_create()
return pl
diff --git a/apis_core/apis_relations/forms2.py b/apis_core/apis_relations/forms2.py
index 9def0a0..7f9d440 100644
--- a/apis_core/apis_relations/forms2.py
+++ b/apis_core/apis_relations/forms2.py
@@ -14,6 +14,7 @@
from django.utils.translation import gettext_lazy as _
from apis_core.apis_entities.fields import ListSelect2
from apis_core.apis_entities.models import AbstractEntity
+
# from dal.autocomplete import ListSelect2
from apis_core.apis_metainfo.models import TempEntityClass, Text, Uri
from apis_core.apis_relations.models import AbstractRelation
@@ -23,7 +24,7 @@
# from dal.autocomplete import ListSelect2
-if 'apis_highlighter' in settings.INSTALLED_APPS:
+if "apis_highlighter" in settings.INSTALLED_APPS:
from apis_highlighter.models import Annotation, AnnotationProject
@@ -31,39 +32,40 @@ def validate_target_autocomplete(value):
try:
value = int(value)
except ValueError:
- if value.startswith('http'):
+ if value.startswith("http"):
test = False
- sett = yaml.load(open(APIS_RDF_URI_SETTINGS, 'r'))
- regx = [x['regex'] for x in sett['mappings']]
- regx.append('http.*oeaw\.ac\.at')
- for k, v in getattr(settings, 'APIS_AC_INSTANCES', {}).items():
- regx.append(v['url'].replace('.', '\.'))
+ sett = yaml.load(open(APIS_RDF_URI_SETTINGS, "r"))
+ regx = [x["regex"] for x in sett["mappings"]]
+ regx.append("http.*oeaw\.ac\.at")
+ for k, v in getattr(settings, "APIS_AC_INSTANCES", {}).items():
+ regx.append(v["url"].replace(".", "\."))
for r in regx:
if re.match(r, value):
test = True
if not test:
if Uri.objects.filter(uri=value).count() != 1:
raise ValidationError(
- _('Invalid value: %(value)s, the url you are using is not configured'),
- code='invalid',
- params={'value': value},
+ _(
+ "Invalid value: %(value)s, the url you are using is not configured"
+ ),
+ code="invalid",
+ params={"value": value},
)
else:
raise ValidationError(
- _('Invalid value: %(value)s, use either URLs or select a value'),
- code='invalid',
- params={'value': value},
+ _("Invalid value: %(value)s, use either URLs or select a value"),
+ code="invalid",
+ params={"value": value},
)
class GenericRelationForm(forms.ModelForm):
-
class Meta:
model = TempEntityClass
- fields = ['start_date_written', 'end_date_written', 'references', 'notes']
+ fields = ["start_date_written", "end_date_written", "references", "notes"]
labels = {
- 'start_date_written': _('Start'),
- 'end_date_written': _('End'),
+ "start_date_written": _("Start"),
+ "end_date_written": _("End"),
}
def save(self, site_instance, instance=None, commit=True):
@@ -83,35 +85,40 @@ def save(self, site_instance, instance=None, commit=True):
x = self.relation_form.objects.get(pk=instance)
else:
x = self.relation_form()
- x.relation_type_id = cd['relation_type']
- x.start_date_written = cd['start_date_written']
- x.end_date_written = cd['end_date_written']
- x.notes = cd['notes']
- x.references = cd['references']
+ x.relation_type_id = cd["relation_type"]
+ x.start_date_written = cd["start_date_written"]
+ x.end_date_written = cd["end_date_written"]
+ x.notes = cd["notes"]
+ x.references = cd["references"]
setattr(x, self.rel_accessor[3], site_instance)
target = AbstractEntity.get_entity_class_of_name(self.rel_accessor[0])
- t1 = target.get_or_create_uri(cd['target'])
+ t1 = target.get_or_create_uri(cd["target"])
if not t1:
- t1 = RDFParser(cd['target'], self.rel_accessor[0]).get_or_create()
+ t1 = RDFParser(cd["target"], self.rel_accessor[0]).get_or_create()
setattr(x, self.rel_accessor[2], t1)
if self.highlighter:
- an_proj = AnnotationProject.objects.get(pk=int(self.request.session.get('annotation_project', 1)))
+ an_proj = AnnotationProject.objects.get(
+ pk=int(self.request.session.get("annotation_project", 1))
+ )
x.published = an_proj.published
if commit:
x.save()
if self.highlighter:
if not commit:
x.save()
- txt = Text.objects.get(pk=cd['HL_text_id'][5:])
+ txt = Text.objects.get(pk=cd["HL_text_id"][5:])
a = Annotation(
- start=cd['HL_start'],
- end=cd['HL_end'],
+ start=cd["HL_start"],
+ end=cd["HL_end"],
text=txt,
user_added=self.request.user,
- annotation_project_id=int(self.request.session.get('annotation_project', 1)))
+ annotation_project_id=int(
+ self.request.session.get("annotation_project", 1)
+ ),
+ )
a.entity_link = x
a.save()
- print('saved: {}'.format(x))
+ print("saved: {}".format(x))
return x
def get_text_id(self):
@@ -119,31 +126,36 @@ def get_text_id(self):
Function to retrieve the highlighted text.
:return: ID of text that was highlighted
"""
- return self.cleaned_data['HL_text_id'][5:]
+ return self.cleaned_data["HL_text_id"][5:]
def get_html_table(self, entity_type, request, site_instance, form_match):
- table = get_generic_relations_table(relation_class=self.relation_form, entity_instance=site_instance, detail=False)
- prefix = re.match(r'([A-Z][a-z])[^A-Z]*([A-Z][a-z])', self.relation_form.__name__)
- prefix = prefix.group(1)+prefix.group(2)+'-'
+ table = get_generic_relations_table(
+ relation_class=self.relation_form,
+ entity_instance=site_instance,
+ detail=False,
+ )
+ prefix = re.match(
+ r"([A-Z][a-z])[^A-Z]*([A-Z][a-z])", self.relation_form.__name__
+ )
+ prefix = prefix.group(1) + prefix.group(2) + "-"
if form_match.group(1) == form_match.group(2):
- dic_a = {'related_'+entity_type.lower()+'A': site_instance}
- dic_b = {'related_' + entity_type.lower() + 'B': site_instance}
- if 'apis_highlighter' in settings.INSTALLED_APPS:
- objects = self.relation_form.objects.filter_ann_proj(request=request).filter(
- Q(**dic_a) | Q(**dic_b)
- )
+ dic_a = {"related_" + entity_type.lower() + "A": site_instance}
+ dic_b = {"related_" + entity_type.lower() + "B": site_instance}
+ if "apis_highlighter" in settings.INSTALLED_APPS:
+ objects = self.relation_form.objects.filter_ann_proj(
+ request=request
+ ).filter(Q(**dic_a) | Q(**dic_b))
else:
- objects = self.relation_form.objects.filter(
- Q(**dic_a) | Q(**dic_b)
- )
+ objects = self.relation_form.objects.filter(Q(**dic_a) | Q(**dic_b))
table_html = table(data=objects, prefix=prefix)
else:
- tab_query = {'related_'+entity_type.lower(): site_instance}
- if 'apis_highlighter' in settings.INSTALLED_APPS:
+ tab_query = {"related_" + entity_type.lower(): site_instance}
+ if "apis_highlighter" in settings.INSTALLED_APPS:
ttab = self.relation_form.objects.filter_ann_proj(
- request=request).filter(**tab_query)
+ request=request
+ ).filter(**tab_query)
else:
ttab = self.relation_form.objects.filter(**tab_query)
table_html = table(data=ttab, prefix=prefix)
@@ -163,154 +175,264 @@ def __init__(self, siteID=None, highlighter=False, *args, **kwargs):
:type instance: object
:type highlighter: bool
"""
- attrs = {'data-placeholder': 'Type to get suggestions',
- 'data-minimum-input-length': getattr(settings, "APIS_MIN_CHAR", 3),
- 'data-html': True,
- 'style': 'width: 100%'}
+ attrs = {
+ "data-placeholder": "Type to get suggestions",
+ "data-minimum-input-length": getattr(settings, "APIS_MIN_CHAR", 3),
+ "data-html": True,
+ "style": "width: 100%",
+ }
help_text_target = "Search and select or use an URL from a reference resource"
attrs_target = copy.deepcopy(attrs)
- attrs_target['data-tags'] = '1'
- css_notes = 'LS'
+ attrs_target["data-tags"] = "1"
+ css_notes = "LS"
self.highlighter = highlighter
- entity_type = kwargs.pop('entity_type')
+ entity_type = kwargs.pop("entity_type")
if type(entity_type) != str:
entity_type = entity_type.__name__
- self.relation_form = kwargs.pop('relation_form')
+ self.relation_form = kwargs.pop("relation_form")
if type(self.relation_form) == str:
- self.relation_form = AbstractRelation.get_relation_class_of_name(self.relation_form)
- self.request = kwargs.pop('request', False)
+ self.relation_form = AbstractRelation.get_relation_class_of_name(
+ self.relation_form
+ )
+ self.request = kwargs.pop("request", False)
super(GenericRelationForm, self).__init__(*args, **kwargs)
- instance = getattr(self, 'instance', None)
- self.fields['relation_type'] = forms.CharField(label='Relation type', required=True)
+ instance = getattr(self, "instance", None)
+ self.fields["relation_type"] = forms.CharField(
+ label="Relation type", required=True
+ )
self.helper = FormHelper()
- self.helper.form_class = '{}Form'.format(str(self.relation_form))
+ self.helper.form_class = "{}Form".format(str(self.relation_form))
self.helper.form_tag = False
- lst_src_target = re.findall('[A-Z][^A-Z]*', self.relation_form.__name__)
+ lst_src_target = re.findall("[A-Z][^A-Z]*", self.relation_form.__name__)
if lst_src_target[0] == lst_src_target[1]:
if instance and instance.id:
- if getattr(instance, 'related_{}A_id'.format(lst_src_target[0].lower())) == int(siteID):
- self.rel_accessor = (lst_src_target[1], True,
- 'related_{}B'.format(lst_src_target[1].lower()),
- 'related_{}A'.format(lst_src_target[0].lower()))
+ if getattr(
+ instance, "related_{}A_id".format(lst_src_target[0].lower())
+ ) == int(siteID):
+ self.rel_accessor = (
+ lst_src_target[1],
+ True,
+ "related_{}B".format(lst_src_target[1].lower()),
+ "related_{}A".format(lst_src_target[0].lower()),
+ )
else:
- self.rel_accessor = (lst_src_target[1], False,
- 'related_{}A'.format(lst_src_target[1].lower()),
- 'related_{}B'.format(lst_src_target[0].lower()))
+ self.rel_accessor = (
+ lst_src_target[1],
+ False,
+ "related_{}A".format(lst_src_target[1].lower()),
+ "related_{}B".format(lst_src_target[0].lower()),
+ )
else:
- self.rel_accessor = (lst_src_target[1], True,
- 'related_{}B'.format(lst_src_target[1].lower()),
- 'related_{}A'.format(lst_src_target[0].lower()))
- self.fields['relation_type'] = autocomplete.Select2ListCreateChoiceField(
- label='Relation type',
+ self.rel_accessor = (
+ lst_src_target[1],
+ True,
+ "related_{}B".format(lst_src_target[1].lower()),
+ "related_{}A".format(lst_src_target[0].lower()),
+ )
+ self.fields["relation_type"] = autocomplete.Select2ListCreateChoiceField(
+ label="Relation type",
widget=ListSelect2(
- #url='/vocabularies/autocomplete/{}{}relation/normal'.format(lst_src_target[0].lower(), lst_src_target[1].lower()),
- url=reverse('apis:apis_vocabularies:generic_vocabularies_autocomplete', args=[''.join([lst_src_target[0].lower(), lst_src_target[1].lower(), 'relation']), 'normal']),
- attrs=attrs))
- self.fields['target'] = autocomplete.Select2ListCreateChoiceField(
+ # url='/vocabularies/autocomplete/{}{}relation/normal'.format(lst_src_target[0].lower(), lst_src_target[1].lower()),
+ url=reverse(
+ "apis:apis_vocabularies:generic_vocabularies_autocomplete",
+ args=[
+ "".join(
+ [
+ lst_src_target[0].lower(),
+ lst_src_target[1].lower(),
+ "relation",
+ ]
+ ),
+ "normal",
+ ],
+ ),
+ attrs=attrs,
+ ),
+ )
+ self.fields["target"] = autocomplete.Select2ListCreateChoiceField(
label=lst_src_target[1],
widget=ListSelect2(
- #url='/entities/autocomplete/{}'.format(lst_src_target[1].lower()),
- url = reverse('apis:apis_entities:generic_entities_autocomplete', args=[lst_src_target[1].lower()]),
- attrs=attrs_target),
+ # url='/entities/autocomplete/{}'.format(lst_src_target[1].lower()),
+ url=reverse(
+ "apis:apis_entities:generic_entities_autocomplete",
+ args=[lst_src_target[1].lower()],
+ ),
+ attrs=attrs_target,
+ ),
validators=[validate_target_autocomplete],
- help_text=help_text_target)
+ help_text=help_text_target,
+ )
elif entity_type.lower() == lst_src_target[0].lower():
- self.rel_accessor = (lst_src_target[1], True,
- 'related_{}'.format(lst_src_target[1].lower()),
- 'related_{}'.format(lst_src_target[0].lower()))
- self.fields['relation_type'] = autocomplete.Select2ListCreateChoiceField(
- label='Relation type',
+ self.rel_accessor = (
+ lst_src_target[1],
+ True,
+ "related_{}".format(lst_src_target[1].lower()),
+ "related_{}".format(lst_src_target[0].lower()),
+ )
+ self.fields["relation_type"] = autocomplete.Select2ListCreateChoiceField(
+ label="Relation type",
widget=ListSelect2(
- #url='/vocabularies/autocomplete/{}{}relation/normal'.format(lst_src_target[0].lower(), lst_src_target[1].lower()),
- url=reverse('apis:apis_vocabularies:generic_vocabularies_autocomplete', args=[''.join([lst_src_target[0].lower(), lst_src_target[1].lower(), 'relation']), 'normal']),
- attrs=attrs))
- self.fields['target'] = autocomplete.Select2ListCreateChoiceField(
+ # url='/vocabularies/autocomplete/{}{}relation/normal'.format(lst_src_target[0].lower(), lst_src_target[1].lower()),
+ url=reverse(
+ "apis:apis_vocabularies:generic_vocabularies_autocomplete",
+ args=[
+ "".join(
+ [
+ lst_src_target[0].lower(),
+ lst_src_target[1].lower(),
+ "relation",
+ ]
+ ),
+ "normal",
+ ],
+ ),
+ attrs=attrs,
+ ),
+ )
+ self.fields["target"] = autocomplete.Select2ListCreateChoiceField(
label=lst_src_target[1],
widget=ListSelect2(
- #url='/entities/autocomplete/{}'.format(lst_src_target[1].lower()),
- url = reverse('apis:apis_entities:generic_entities_autocomplete', args=[lst_src_target[1].lower()]),
- attrs=attrs_target),
+ # url='/entities/autocomplete/{}'.format(lst_src_target[1].lower()),
+ url=reverse(
+ "apis:apis_entities:generic_entities_autocomplete",
+ args=[lst_src_target[1].lower()],
+ ),
+ attrs=attrs_target,
+ ),
validators=[validate_target_autocomplete],
- help_text=help_text_target)
+ help_text=help_text_target,
+ )
elif entity_type.lower() == lst_src_target[1].lower():
- self.rel_accessor = (lst_src_target[0], False,
- 'related_{}'.format(lst_src_target[0].lower()),
- 'related_{}'.format(lst_src_target[1].lower()))
- self.fields['relation_type'] = autocomplete.Select2ListCreateChoiceField(
- label='Relation type',
+ self.rel_accessor = (
+ lst_src_target[0],
+ False,
+ "related_{}".format(lst_src_target[0].lower()),
+ "related_{}".format(lst_src_target[1].lower()),
+ )
+ self.fields["relation_type"] = autocomplete.Select2ListCreateChoiceField(
+ label="Relation type",
widget=ListSelect2(
- #url='/vocabularies/autocomplete/{}{}relation/reverse'.format(lst_src_target[0].lower(), lst_src_target[1].lower()),
- url=reverse('apis:apis_vocabularies:generic_vocabularies_autocomplete', args=[''.join([lst_src_target[0].lower(), lst_src_target[1].lower(), 'relation']), 'reverse']),
- attrs=attrs))
- self.fields['target'] = autocomplete.Select2ListCreateChoiceField(
+ # url='/vocabularies/autocomplete/{}{}relation/reverse'.format(lst_src_target[0].lower(), lst_src_target[1].lower()),
+ url=reverse(
+ "apis:apis_vocabularies:generic_vocabularies_autocomplete",
+ args=[
+ "".join(
+ [
+ lst_src_target[0].lower(),
+ lst_src_target[1].lower(),
+ "relation",
+ ]
+ ),
+ "reverse",
+ ],
+ ),
+ attrs=attrs,
+ ),
+ )
+ self.fields["target"] = autocomplete.Select2ListCreateChoiceField(
label=lst_src_target[0],
widget=ListSelect2(
- #url='/entities/autocomplete/{}'.format(lst_src_target[0].lower()),
- url = reverse('apis:apis_entities:generic_entities_autocomplete', args=[lst_src_target[0].lower()]),
- attrs=attrs_target),
+ # url='/entities/autocomplete/{}'.format(lst_src_target[0].lower()),
+ url=reverse(
+ "apis:apis_entities:generic_entities_autocomplete",
+ args=[lst_src_target[0].lower()],
+ ),
+ attrs=attrs_target,
+ ),
validators=[validate_target_autocomplete],
- help_text=help_text_target)
+ help_text=help_text_target,
+ )
else:
- print('no hit rel_accessor')
+ print("no hit rel_accessor")
if instance and instance.id:
- self.fields['target'].choices = [
- (str(Uri.objects.filter(entity=getattr(instance, self.rel_accessor[2]))[0]),
- str(getattr(instance, self.rel_accessor[2])))]
- self.fields['target'].initial = (str(Uri.objects.filter(entity=getattr(instance, self.rel_accessor[2]))[0]),
- str(getattr(instance, self.rel_accessor[2])))
+ self.fields["target"].choices = [
+ (
+ str(
+ Uri.objects.filter(
+ entity=getattr(instance, self.rel_accessor[2])
+ )[0]
+ ),
+ str(getattr(instance, self.rel_accessor[2])),
+ )
+ ]
+ self.fields["target"].initial = (
+ str(
+ Uri.objects.filter(entity=getattr(instance, self.rel_accessor[2]))[
+ 0
+ ]
+ ),
+ str(getattr(instance, self.rel_accessor[2])),
+ )
if self.rel_accessor[1]:
- self.fields['relation_type'].choices = [(instance.relation_type.id,
- instance.relation_type.label)]
- self.fields['relation_type'].initial = (instance.relation_type.id, instance.relation_type.label)
+ self.fields["relation_type"].choices = [
+ (instance.relation_type.id, instance.relation_type.label)
+ ]
+ self.fields["relation_type"].initial = (
+ instance.relation_type.id,
+ instance.relation_type.label,
+ )
else:
- self.fields['relation_type'].choices = [(instance.relation_type.id,
- instance.relation_type.label_reverse)]
- self.fields['relation_type'].initial = (instance.relation_type.id, instance.relation_type.label_reverse)
+ self.fields["relation_type"].choices = [
+ (instance.relation_type.id, instance.relation_type.label_reverse)
+ ]
+ self.fields["relation_type"].initial = (
+ instance.relation_type.id,
+ instance.relation_type.label_reverse,
+ )
if highlighter:
- css_notes = 'HL'
+ css_notes = "HL"
self.helper.include_media = False
self.helper.layout = Layout(
- 'relation_type',
- 'target',
- 'start_date_written',
- 'end_date_written',
+ "relation_type",
+ "target",
+ "start_date_written",
+ "end_date_written",
Accordion(
AccordionGroup(
- 'Notes and References',
- 'notes',
- 'references',
+ "Notes and References",
+ "notes",
+ "references",
active=False,
- css_id="{}_{}_notes_refs".format(self.relation_form.__name__, css_notes))))
+ css_id="{}_{}_notes_refs".format(
+ self.relation_form.__name__, css_notes
+ ),
+ )
+ ),
+ )
if highlighter:
- self.fields['HL_start'] = forms.IntegerField(widget=forms.HiddenInput)
- self.fields['HL_end'] = forms.IntegerField(widget=forms.HiddenInput)
- self.fields['HL_text_id'] = forms.CharField(widget=forms.HiddenInput)
- self.helper.layout.extend([
- 'HL_start',
- 'HL_end',
- 'HL_text_id'])
-
+ self.fields["HL_start"] = forms.IntegerField(widget=forms.HiddenInput)
+ self.fields["HL_end"] = forms.IntegerField(widget=forms.HiddenInput)
+ self.fields["HL_text_id"] = forms.CharField(widget=forms.HiddenInput)
+ self.helper.layout.extend(["HL_start", "HL_end", "HL_text_id"])
if instance != None:
if instance.start_date_written:
- self.fields['start_date_written'].help_text = DateParser.get_date_help_text_from_dates(
+ self.fields[
+ "start_date_written"
+ ].help_text = DateParser.get_date_help_text_from_dates(
single_date=instance.start_date,
single_start_date=instance.start_start_date,
single_end_date=instance.start_end_date,
single_date_written=instance.start_date_written,
)
else:
- self.fields['start_date_written'].help_text = DateParser.get_date_help_text_default()
+ self.fields[
+ "start_date_written"
+ ].help_text = DateParser.get_date_help_text_default()
if instance.end_date_written:
- self.fields['end_date_written'].help_text = DateParser.get_date_help_text_from_dates(
+ self.fields[
+ "end_date_written"
+ ].help_text = DateParser.get_date_help_text_from_dates(
single_date=instance.end_date,
single_start_date=instance.end_start_date,
single_end_date=instance.end_end_date,
single_date_written=instance.end_date_written,
)
else:
- self.fields['end_date_written'].help_text = DateParser.get_date_help_text_default()
+ self.fields[
+ "end_date_written"
+ ].help_text = DateParser.get_date_help_text_default()
diff --git a/apis_core/apis_relations/migrations/0001_initial.py b/apis_core/apis_relations/migrations/0001_initial.py
index c94815c..e366d1a 100644
--- a/apis_core/apis_relations/migrations/0001_initial.py
+++ b/apis_core/apis_relations/migrations/0001_initial.py
@@ -9,206 +9,374 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ('apis_entities', '0001_initial'),
- ('apis_metainfo', '0001_initial'),
+ ("apis_entities", "0001_initial"),
+ ("apis_metainfo", "0001_initial"),
]
operations = [
migrations.CreateModel(
- name='EventEvent',
+ name="EventEvent",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='EventWork',
+ name="EventWork",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='InstitutionEvent',
+ name="InstitutionEvent",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='InstitutionInstitution',
+ name="InstitutionInstitution",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='InstitutionPlace',
+ name="InstitutionPlace",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='InstitutionWork',
+ name="InstitutionWork",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PersonEvent',
+ name="PersonEvent",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PersonInstitution',
+ name="PersonInstitution",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PersonPerson',
+ name="PersonPerson",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PersonPlace',
+ name="PersonPlace",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PersonWork',
+ name="PersonWork",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PlaceEvent',
+ name="PlaceEvent",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PlacePlace',
+ name="PlacePlace",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='PlaceWork',
+ name="PlaceWork",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
migrations.CreateModel(
- name='WorkWork',
+ name="WorkWork",
fields=[
- ('tempentityclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_metainfo.TempEntityClass')),
- ('related_workA', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_workB', to='apis_entities.Work')),
- ('related_workB', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_workA', to='apis_entities.Work')),
+ (
+ "tempentityclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_metainfo.TempEntityClass",
+ ),
+ ),
+ (
+ "related_workA",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_workB",
+ to="apis_entities.Work",
+ ),
+ ),
+ (
+ "related_workB",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_workA",
+ to="apis_entities.Work",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_metainfo.tempentityclass',),
+ bases=("apis_metainfo.tempentityclass",),
managers=[
- ('annotation_links', django.db.models.manager.Manager()),
+ ("annotation_links", django.db.models.manager.Manager()),
],
),
]
diff --git a/apis_core/apis_relations/migrations/0002_auto_20200121_1227.py b/apis_core/apis_relations/migrations/0002_auto_20200121_1227.py
index 9979e76..dc9f6e8 100644
--- a/apis_core/apis_relations/migrations/0002_auto_20200121_1227.py
+++ b/apis_core/apis_relations/migrations/0002_auto_20200121_1227.py
@@ -9,225 +9,483 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ('apis_vocabularies', '0001_initial'),
- ('apis_relations', '0001_initial'),
- ('apis_entities', '0002_auto_20200121_1227'),
+ ("apis_vocabularies", "0001_initial"),
+ ("apis_relations", "0001_initial"),
+ ("apis_entities", "0002_auto_20200121_1227"),
]
operations = [
migrations.AddField(
- model_name='workwork',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='workwork_set', to='apis_vocabularies.WorkWorkRelation'),
- ),
- migrations.AddField(
- model_name='placework',
- name='related_place',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placework_set', to='apis_entities.Place'),
- ),
- migrations.AddField(
- model_name='placework',
- name='related_work',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placework_set', to='apis_entities.Work'),
- ),
- migrations.AddField(
- model_name='placework',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placework_set', to='apis_vocabularies.PlaceWorkRelation'),
- ),
- migrations.AddField(
- model_name='placeplace',
- name='related_placeA',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_placeB', to='apis_entities.Place'),
- ),
- migrations.AddField(
- model_name='placeplace',
- name='related_placeB',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_placeA', to='apis_entities.Place'),
- ),
- migrations.AddField(
- model_name='placeplace',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placeplace_set', to='apis_vocabularies.PlacePlaceRelation'),
- ),
- migrations.AddField(
- model_name='placeevent',
- name='related_event',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placeevent_set', to='apis_entities.Event'),
- ),
- migrations.AddField(
- model_name='placeevent',
- name='related_place',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placeevent_set', to='apis_entities.Place'),
- ),
- migrations.AddField(
- model_name='placeevent',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='placeevent_set', to='apis_vocabularies.PlaceEventRelation'),
- ),
- migrations.AddField(
- model_name='personwork',
- name='related_person',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personwork_set', to='apis_entities.Person'),
- ),
- migrations.AddField(
- model_name='personwork',
- name='related_work',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personwork_set', to='apis_entities.Work'),
- ),
- migrations.AddField(
- model_name='personwork',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personwork_set', to='apis_vocabularies.PersonWorkRelation'),
- ),
- migrations.AddField(
- model_name='personplace',
- name='related_person',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personplace_set', to='apis_entities.Person'),
- ),
- migrations.AddField(
- model_name='personplace',
- name='related_place',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personplace_set', to='apis_entities.Place'),
- ),
- migrations.AddField(
- model_name='personplace',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personplace_set', to='apis_vocabularies.PersonPlaceRelation'),
- ),
- migrations.AddField(
- model_name='personperson',
- name='related_personA',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_personB', to='apis_entities.Person'),
- ),
- migrations.AddField(
- model_name='personperson',
- name='related_personB',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_personA', to='apis_entities.Person'),
- ),
- migrations.AddField(
- model_name='personperson',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personperson_set', to='apis_vocabularies.PersonPersonRelation'),
- ),
- migrations.AddField(
- model_name='personinstitution',
- name='related_institution',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personinstitution_set', to='apis_entities.Institution'),
- ),
- migrations.AddField(
- model_name='personinstitution',
- name='related_person',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personinstitution_set', to='apis_entities.Person'),
- ),
- migrations.AddField(
- model_name='personinstitution',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personinstitution_set', to='apis_vocabularies.PersonInstitutionRelation'),
- ),
- migrations.AddField(
- model_name='personevent',
- name='related_event',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personevent_set', to='apis_entities.Event'),
- ),
- migrations.AddField(
- model_name='personevent',
- name='related_person',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personevent_set', to='apis_entities.Person'),
- ),
- migrations.AddField(
- model_name='personevent',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='personevent_set', to='apis_vocabularies.PersonEventRelation'),
- ),
- migrations.AddField(
- model_name='institutionwork',
- name='related_institution',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionwork_set', to='apis_entities.Institution'),
- ),
- migrations.AddField(
- model_name='institutionwork',
- name='related_work',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionwork_set', to='apis_entities.Work'),
- ),
- migrations.AddField(
- model_name='institutionwork',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionwork_set', to='apis_vocabularies.InstitutionWorkRelation'),
- ),
- migrations.AddField(
- model_name='institutionplace',
- name='related_institution',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionplace_set', to='apis_entities.Institution'),
- ),
- migrations.AddField(
- model_name='institutionplace',
- name='related_place',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionplace_set', to='apis_entities.Place'),
- ),
- migrations.AddField(
- model_name='institutionplace',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionplace_set', to='apis_vocabularies.InstitutionPlaceRelation'),
- ),
- migrations.AddField(
- model_name='institutioninstitution',
- name='related_institutionA',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_institutionB', to='apis_entities.Institution'),
- ),
- migrations.AddField(
- model_name='institutioninstitution',
- name='related_institutionB',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_institutionA', to='apis_entities.Institution'),
- ),
- migrations.AddField(
- model_name='institutioninstitution',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutioninstitution_set', to='apis_vocabularies.InstitutionInstitutionRelation'),
- ),
- migrations.AddField(
- model_name='institutionevent',
- name='related_event',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionevent_set', to='apis_entities.Event'),
- ),
- migrations.AddField(
- model_name='institutionevent',
- name='related_institution',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionevent_set', to='apis_entities.Institution'),
- ),
- migrations.AddField(
- model_name='institutionevent',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='institutionevent_set', to='apis_vocabularies.InstitutionEventRelation'),
- ),
- migrations.AddField(
- model_name='eventwork',
- name='related_event',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='eventwork_set', to='apis_entities.Event'),
- ),
- migrations.AddField(
- model_name='eventwork',
- name='related_work',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='eventwork_set', to='apis_entities.Work'),
- ),
- migrations.AddField(
- model_name='eventwork',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='eventwork_set', to='apis_vocabularies.EventWorkRelation'),
- ),
- migrations.AddField(
- model_name='eventevent',
- name='related_eventA',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_eventB', to='apis_entities.Event'),
- ),
- migrations.AddField(
- model_name='eventevent',
- name='related_eventB',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='related_eventA', to='apis_entities.Event'),
- ),
- migrations.AddField(
- model_name='eventevent',
- name='relation_type',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='eventevent_set', to='apis_vocabularies.EventEventRelation'),
+ model_name="workwork",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="workwork_set",
+ to="apis_vocabularies.WorkWorkRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placework",
+ name="related_place",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placework_set",
+ to="apis_entities.Place",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placework",
+ name="related_work",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placework_set",
+ to="apis_entities.Work",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placework",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placework_set",
+ to="apis_vocabularies.PlaceWorkRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placeplace",
+ name="related_placea",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_placeb",
+ to="apis_entities.Place",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placeplace",
+ name="related_placeb",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_placea",
+ to="apis_entities.Place",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placeplace",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placeplace_set",
+ to="apis_vocabularies.PlacePlaceRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placeevent",
+ name="related_event",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placeevent_set",
+ to="apis_entities.Event",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placeevent",
+ name="related_place",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placeevent_set",
+ to="apis_entities.Place",
+ ),
+ ),
+ migrations.AddField(
+ model_name="placeevent",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="placeevent_set",
+ to="apis_vocabularies.PlaceEventRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personwork",
+ name="related_person",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personwork_set",
+ to="apis_entities.Person",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personwork",
+ name="related_work",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personwork_set",
+ to="apis_entities.Work",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personwork",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personwork_set",
+ to="apis_vocabularies.PersonWorkRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personplace",
+ name="related_person",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personplace_set",
+ to="apis_entities.Person",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personplace",
+ name="related_place",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personplace_set",
+ to="apis_entities.Place",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personplace",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personplace_set",
+ to="apis_vocabularies.PersonPlaceRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personperson",
+ name="related_persona",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_personb",
+ to="apis_entities.Person",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personperson",
+ name="related_personb",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_persona",
+ to="apis_entities.Person",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personperson",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personperson_set",
+ to="apis_vocabularies.PersonPersonRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personinstitution",
+ name="related_institution",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personinstitution_set",
+ to="apis_entities.Institution",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personinstitution",
+ name="related_person",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personinstitution_set",
+ to="apis_entities.Person",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personinstitution",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personinstitution_set",
+ to="apis_vocabularies.PersonInstitutionRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personevent",
+ name="related_event",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personevent_set",
+ to="apis_entities.Event",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personevent",
+ name="related_person",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personevent_set",
+ to="apis_entities.Person",
+ ),
+ ),
+ migrations.AddField(
+ model_name="personevent",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="personevent_set",
+ to="apis_vocabularies.PersonEventRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionwork",
+ name="related_institution",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionwork_set",
+ to="apis_entities.Institution",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionwork",
+ name="related_work",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionwork_set",
+ to="apis_entities.Work",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionwork",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionwork_set",
+ to="apis_vocabularies.InstitutionWorkRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionplace",
+ name="related_institution",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionplace_set",
+ to="apis_entities.Institution",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionplace",
+ name="related_place",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionplace_set",
+ to="apis_entities.Place",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionplace",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionplace_set",
+ to="apis_vocabularies.InstitutionPlaceRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutioninstitution",
+ name="related_institutionA",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_institutionB",
+ to="apis_entities.Institution",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutioninstitution",
+ name="related_institutionB",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_institutionA",
+ to="apis_entities.Institution",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutioninstitution",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutioninstitution_set",
+ to="apis_vocabularies.InstitutionInstitutionRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionevent",
+ name="related_event",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionevent_set",
+ to="apis_entities.Event",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionevent",
+ name="related_institution",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionevent_set",
+ to="apis_entities.Institution",
+ ),
+ ),
+ migrations.AddField(
+ model_name="institutionevent",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="institutionevent_set",
+ to="apis_vocabularies.InstitutionEventRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="eventwork",
+ name="related_event",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="eventwork_set",
+ to="apis_entities.Event",
+ ),
+ ),
+ migrations.AddField(
+ model_name="eventwork",
+ name="related_work",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="eventwork_set",
+ to="apis_entities.Work",
+ ),
+ ),
+ migrations.AddField(
+ model_name="eventwork",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="eventwork_set",
+ to="apis_vocabularies.EventWorkRelation",
+ ),
+ ),
+ migrations.AddField(
+ model_name="eventevent",
+ name="related_eventa",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_eventb",
+ to="apis_entities.Event",
+ ),
+ ),
+ migrations.AddField(
+ model_name="eventevent",
+ name="related_eventb",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="related_eventa",
+ to="apis_entities.Event",
+ ),
+ ),
+ migrations.AddField(
+ model_name="eventevent",
+ name="relation_type",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="eventevent_set",
+ to="apis_vocabularies.EventEventRelation",
+ ),
),
]
diff --git a/apis_core/apis_relations/migrations/0003_auto_20200609_0925.py b/apis_core/apis_relations/migrations/0003_auto_20200609_0925.py
index 14436f3..4e76a17 100644
--- a/apis_core/apis_relations/migrations/0003_auto_20200609_0925.py
+++ b/apis_core/apis_relations/migrations/0003_auto_20200609_0925.py
@@ -6,143 +6,128 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_relations', '0002_auto_20200121_1227'),
+ ("apis_relations", "0002_auto_20200121_1227"),
]
operations = [
migrations.AlterModelOptions(
- name='eventevent',
- options={'default_manager_name': 'objects'},
+ name="eventevent",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='eventwork',
- options={'default_manager_name': 'objects'},
+ name="eventwork",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='institutionevent',
- options={'default_manager_name': 'objects'},
+ name="institutionevent",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='institutioninstitution',
- options={'default_manager_name': 'objects'},
+ name="institutioninstitution",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='institutionplace',
- options={'default_manager_name': 'objects'},
+ name="institutionplace",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='institutionwork',
- options={'default_manager_name': 'objects'},
+ name="institutionwork",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='personevent',
- options={'default_manager_name': 'objects'},
+ name="personevent",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='personinstitution',
- options={'default_manager_name': 'objects'},
+ name="personinstitution",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='personperson',
- options={'default_manager_name': 'objects'},
+ name="personperson",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='personplace',
- options={'default_manager_name': 'objects'},
+ name="personplace",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='personwork',
- options={'default_manager_name': 'objects'},
+ name="personwork",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='placeevent',
- options={'default_manager_name': 'objects'},
+ name="placeevent",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='placeplace',
- options={'default_manager_name': 'objects'},
+ name="placeplace",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='placework',
- options={'default_manager_name': 'objects'},
+ name="placework",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelOptions(
- name='workwork',
- options={'default_manager_name': 'objects'},
+ name="workwork",
+ options={"default_manager_name": "objects"},
),
migrations.AlterModelManagers(
- name='eventevent',
- managers=[
- ],
+ name="eventevent",
+ managers=[],
),
migrations.AlterModelManagers(
- name='eventwork',
- managers=[
- ],
+ name="eventwork",
+ managers=[],
),
migrations.AlterModelManagers(
- name='institutionevent',
- managers=[
- ],
+ name="institutionevent",
+ managers=[],
),
migrations.AlterModelManagers(
- name='institutioninstitution',
- managers=[
- ],
+ name="institutioninstitution",
+ managers=[],
),
migrations.AlterModelManagers(
- name='institutionplace',
- managers=[
- ],
+ name="institutionplace",
+ managers=[],
),
migrations.AlterModelManagers(
- name='institutionwork',
- managers=[
- ],
+ name="institutionwork",
+ managers=[],
),
migrations.AlterModelManagers(
- name='personevent',
- managers=[
- ],
+ name="personevent",
+ managers=[],
),
migrations.AlterModelManagers(
- name='personinstitution',
- managers=[
- ],
+ name="personinstitution",
+ managers=[],
),
migrations.AlterModelManagers(
- name='personperson',
- managers=[
- ],
+ name="personperson",
+ managers=[],
),
migrations.AlterModelManagers(
- name='personplace',
- managers=[
- ],
+ name="personplace",
+ managers=[],
),
migrations.AlterModelManagers(
- name='personwork',
- managers=[
- ],
+ name="personwork",
+ managers=[],
),
migrations.AlterModelManagers(
- name='placeevent',
- managers=[
- ],
+ name="placeevent",
+ managers=[],
),
migrations.AlterModelManagers(
- name='placeplace',
- managers=[
- ],
+ name="placeplace",
+ managers=[],
),
migrations.AlterModelManagers(
- name='placework',
- managers=[
- ],
+ name="placework",
+ managers=[],
),
migrations.AlterModelManagers(
- name='workwork',
- managers=[
- ],
+ name="workwork",
+ managers=[],
),
]
diff --git a/apis_core/apis_relations/models.py b/apis_core/apis_relations/models.py
index 5c3f941..4634e4e 100644
--- a/apis_core/apis_relations/models.py
+++ b/apis_core/apis_relations/models.py
@@ -9,8 +9,6 @@
from apis_core.apis_metainfo.models import TempEntityClass
-
-
#######################################################################
#
# AbstractRelation
@@ -24,60 +22,62 @@ class AbstractRelation(TempEntityClass):
relating to either all or specific relations.
"""
- #annotation_links = AnnotationRelationLinkManager()
+ # annotation_links = AnnotationRelationLinkManager()
class Meta:
abstract = True
- default_manager_name = 'objects'
+ default_manager_name = "objects"
def save(self, *args, **kwargs):
if (
- getattr(self, self.get_related_entity_field_nameA()) is None
- or getattr(self, self.get_related_entity_field_nameB()) is None
+ getattr(self, self.get_related_entity_field_namea()) is None
+ or getattr(self, self.get_related_entity_field_nameb()) is None
or self.relation_type is None
):
raise Exception("One or more of the necessary related models are None")
super().save(*args, **kwargs)
-
# Methods dealing with individual data retrievals of instances
####################################################################################################################
def __str__(self):
- return "{} ({}) {}".format(self.get_related_entity_instanceA(), self.relation_type, self.get_related_entity_instanceB())
-
+ return "{} ({}) {}".format(
+ self.get_related_entity_instancea(),
+ self.relation_type,
+ self.get_related_entity_instanceb(),
+ )
def get_web_object(self):
- nameA = self.get_related_entity_instanceA().name
- nameB = self.get_related_entity_instanceB().name
+ namea = self.get_related_entity_instancea().name
+ nameb = self.get_related_entity_instanceb().name
- if self.get_related_entity_classA() == Person:
- nameA += ", "
- if self.get_related_entity_instanceA().first_name is None:
- nameA += "-"
+ if self.get_related_entity_classa() == Person:
+ namea += ", "
+ if self.get_related_entity_instancea().first_name is None:
+ namea += "-"
else:
- nameA += self.get_related_entity_instanceA().first_name
+ namea += self.get_related_entity_instancea().first_name
- if self.get_related_entity_classB() == Person:
- nameB += ", "
- if self.get_related_entity_instanceB().first_name is None:
- nameB += "-"
+ if self.get_related_entity_classb() == Person:
+ nameb += ", "
+ if self.get_related_entity_instanceb().first_name is None:
+ nameb += "-"
else:
- nameB += self.get_related_entity_instanceB().first_name
+ nameb += self.get_related_entity_instanceb().first_name
result = {
- 'relation_pk': self.pk,
- 'relation_type': self.relation_type.name,
- self.get_related_entity_field_nameA(): nameA,
- self.get_related_entity_field_nameB(): nameB,
- 'start_date': self.start_date_written,
- 'end_date': self.end_date_written}
+ "relation_pk": self.pk,
+ "relation_type": self.relation_type.name,
+ self.get_related_entity_field_namea(): namea,
+ self.get_related_entity_field_nameb(): nameb,
+ "start_date": self.start_date_written,
+ "end_date": self.end_date_written,
+ }
return result
-
def get_table_dict(self, entity):
"""Dict for the tabels in the html view
@@ -85,41 +85,39 @@ def get_table_dict(self, entity):
and which one the related.
:return:
"""
- if self.get_related_entity_instanceA() == entity:
- rel_other_key = self.get_related_entity_field_nameB()[:-1]
- rel_other_value = self.get_related_entity_instanceB()
+ if self.get_related_entity_instancea() == entity:
+ rel_other_key = self.get_related_entity_field_nameb()[:-1]
+ rel_other_value = self.get_related_entity_instanceb()
rel_type = self.relation_type.label
- elif self.get_related_entity_instanceB() == entity:
- rel_other_key = self.get_related_entity_field_nameA()[:-1]
- rel_other_value = self.get_related_entity_instanceA()
+ elif self.get_related_entity_instanceb() == entity:
+ rel_other_key = self.get_related_entity_field_namea()[:-1]
+ rel_other_value = self.get_related_entity_instancea()
rel_type = self.relation_type.label_reverse
else:
- raise Exception("Did not find corresponding entity. Wiring of current relation to current entity is faulty.")
+ raise Exception(
+ "Did not find corresponding entity. Wiring of current relation to current entity is faulty."
+ )
result = {
- 'relation_pk': self.pk,
- 'relation_type': rel_type,
+ "relation_pk": self.pk,
+ "relation_type": rel_type,
rel_other_key: rel_other_value,
- 'start_date_written': self.start_date_written,
- 'end_date_written': self.end_date_written,
- 'start_date': self.start_date,
- 'end_date': self.end_date}
+ "start_date_written": self.start_date_written,
+ "end_date_written": self.end_date_written,
+ "start_date": self.start_date,
+ "end_date": self.end_date,
+ }
return result
-
-
# Various Methods enabling convenient shortcuts between entities, relations, fields, etc
####################################################################################################################
-
# Methods dealing with all relations
####################################################################################################################
-
_all_relation_classes = None
_all_relation_names = None
-
@classmethod
def get_all_relation_classes(cls):
"""
@@ -137,16 +135,17 @@ def get_all_relation_classes(cls):
# using python's reflective logic, the following loop iterates over all classes of this current module.
for relation_name, relation_class in inspect.getmembers(
- sys.modules[__name__], inspect.isclass):
- print('inspecting classes')
+ sys.modules[__name__], inspect.isclass
+ ):
# check for python classes not to be used.
- if \
- relation_class.__module__ == "apis_core.apis_relations.models" and \
- relation_class.__name__ != "AnnotationRelationLinkManager" and \
- relation_class.__name__ != "BaseRelationManager" and \
- relation_class.__name__ != "RelationPublishedQueryset" and \
- relation_class.__name__ != "AbstractRelation" and \
- relation_name != "ent_class":
+ if (
+ relation_class.__module__ == "apis_core.apis_relations.models"
+ and relation_class.__name__ != "AnnotationRelationLinkManager"
+ and relation_class.__name__ != "BaseRelationManager"
+ and relation_class.__name__ != "RelationPublishedQueryset"
+ and relation_class.__name__ != "AbstractRelation"
+ and relation_name != "ent_class"
+ ):
relation_classes.append(relation_class)
relation_names.append(relation_name.lower())
@@ -156,7 +155,6 @@ def get_all_relation_classes(cls):
return cls._all_relation_classes
-
@classmethod
def get_relation_class_of_name(cls, relation_name):
"""
@@ -170,7 +168,6 @@ def get_relation_class_of_name(cls, relation_name):
raise Exception("Could not find relation class of name:", relation_name)
-
@classmethod
def get_all_relation_names(cls):
"""
@@ -185,17 +182,13 @@ def get_all_relation_names(cls):
return cls._all_relation_names
-
-
# Methods dealing with related relations and entities
####################################################################################################################
-
_relation_classes_of_entity_class = {}
_relation_classes_of_entity_name = {}
_relation_field_names_of_entity_class = {}
-
@classmethod
def get_relation_classes_of_entity_class(cls, entity_class):
"""
@@ -208,7 +201,6 @@ def get_relation_classes_of_entity_class(cls, entity_class):
return cls._relation_classes_of_entity_class[entity_class]
-
@classmethod
def get_relation_classes_of_entity_name(cls, entity_name):
"""
@@ -221,7 +213,6 @@ def get_relation_classes_of_entity_name(cls, entity_name):
return cls._relation_classes_of_entity_name[entity_name.lower()]
-
@classmethod
def add_relation_class_of_entity_class(cls, entity_class):
"""
@@ -233,15 +224,18 @@ def add_relation_class_of_entity_class(cls, entity_class):
"""
# get the list of the class dictionary, create if not yet exists.
- relation_class_list = cls._relation_classes_of_entity_class.get(entity_class, [])
+ relation_class_list = cls._relation_classes_of_entity_class.get(
+ entity_class, []
+ )
# append the current relation class to the list.
relation_class_list.append(cls)
# save into the dictionary, which uses the entity class as key and the extended list above as value.
cls._relation_classes_of_entity_class[entity_class] = relation_class_list
- cls._relation_classes_of_entity_name[entity_class.__name__.lower()] = relation_class_list
-
+ cls._relation_classes_of_entity_name[
+ entity_class.__name__.lower()
+ ] = relation_class_list
@classmethod
def get_relation_field_names_of_entity_class(cls, entity_class):
@@ -250,12 +244,11 @@ def get_relation_field_names_of_entity_class(cls, entity_class):
:return: a list of relation class field names that are related to the entity class
E.g. AbstractRelation.get_relation_names_of_entity_class( Person )
- -> [ personevent_set, personinstitution_set, related_personA, related_personB, personplace_set, personwork_set ]
+ -> [ personevent_set, personinstitution_set, related_persona, related_personb, personplace_set, personwork_set ]
"""
return cls._relation_field_names_of_entity_class[entity_class]
-
@classmethod
def add_relation_field_name_of_entity_class(cls, relation_name, entity_class):
"""
@@ -267,51 +260,51 @@ def add_relation_field_name_of_entity_class(cls, relation_name, entity_class):
"""
# get the list of the class dictionary, create if not yet exists.
- relation_names_list = cls._relation_field_names_of_entity_class.get(entity_class, [])
+ relation_names_list = cls._relation_field_names_of_entity_class.get(
+ entity_class, []
+ )
# append the current relation field name to the list.
- if relation_name not in relation_names_list:
- relation_names_list.append(relation_name) #TODO: this is a workaround, find out why it is called several times
+ if relation_name not in relation_names_list:
+ relation_names_list.append(
+ relation_name
+ ) # TODO: this is a workaround, find out why it is called several times
# save into the dictionary, which uses the entity class as key and the extended list above as value.
cls._relation_field_names_of_entity_class[entity_class] = relation_names_list
-
- def get_related_entity_instanceA(self):
+ def get_related_entity_instancea(self):
"""
This method only works on the relation instance of a given relation class.
There it returns the instance of an entity on the 'A' side of the given relation instance.
Note that if your IDE complains about expecting a 'str' instead of 'None' this happens because
- the method 'get_related_entity_field_nameA()' is only implemented and overridden at runtime in the
+ the method 'get_related_entity_field_namea()' is only implemented and overridden at runtime in the
function 'generate_all_fields' in the class 'EntityRelationFieldGenerator'.
:return: An entity instance related to the current relation instance
"""
- return getattr( self, self.get_related_entity_field_nameA() )
+ print(f"{self.get_related_entity_field_namea()}")
+ return getattr(self, self.get_related_entity_field_namea())
-
- def get_related_entity_instanceB(self):
+ def get_related_entity_instanceb(self):
"""
This method only works on the relation instance of a given relation class.
There it returns the instance of an entity on the 'B' side of the given relation instance.
Note that if your IDE complains about expecting a 'str' instead of 'None' this happens because
- the method 'get_related_entity_field_nameB()' is only implemented and overridden at runtime in the
+ the method 'get_related_entity_field_nameb()' is only implemented and overridden at runtime in the
function 'generate_all_fields' in the class 'EntityRelationFieldGenerator'.
:return: An entity instance related to the current relation instance
"""
- return getattr( self, self.get_related_entity_field_nameB() )
-
-
+ return getattr(self, self.get_related_entity_field_nameb())
# method stumps
####################################################################################################################
# These stumps merely serve as placeholders so that both IDE and developers know that these methods exist.
# They are implemented programmatically in the function 'generate_all_fields' in the class 'EntityRelationFieldGenerator'.
-
@classmethod
- def get_related_entity_classA(cls):
+ def get_related_entity_classa(cls):
"""
:return: the python class of the A side of the current relation class or instance
E.g. PersonWork -> Person
@@ -319,7 +312,7 @@ def get_related_entity_classA(cls):
return None
@classmethod
- def get_related_entity_classB(cls):
+ def get_related_entity_classb(cls):
"""
:return: the python class of the B side of the current relation class or instance
E.g. PersonWork -> Work
@@ -327,15 +320,16 @@ def get_related_entity_classB(cls):
return None
@classmethod
- def get_related_entity_field_nameA(cls):
+ def get_related_entity_field_namea(cls):
"""
:return: the name of the field of the A side of the current relation class or instance
E.g. PersonWork -> "related_person"
"""
+ print(dir(cls))
return None
@classmethod
- def get_related_entity_field_nameB(cls):
+ def get_related_entity_field_nameb(cls):
"""
:return: the name of the field of the B side of the current relation class or instance
E.g. PersonWork -> "related_work"
@@ -343,8 +337,6 @@ def get_related_entity_field_nameB(cls):
return None
-
-
#######################################################################
#
# Person - ... - Relation
@@ -452,4 +444,4 @@ class EventWork(AbstractRelation):
class WorkWork(AbstractRelation):
- pass
\ No newline at end of file
+ pass
diff --git a/apis_core/apis_relations/rel_filters.py b/apis_core/apis_relations/rel_filters.py
index a54b17a..f6b6984 100644
--- a/apis_core/apis_relations/rel_filters.py
+++ b/apis_core/apis_relations/rel_filters.py
@@ -12,6 +12,7 @@
# TODO __sresch__ : Change this whole module according to the same logic as in apis_core/apis_entities/filters.py
+
def get_excluded_fields(model):
modelname = model.__name__
base_list = getattr(settings, "APIS_RELATIONS_FILTER_EXCLUDE", [])
@@ -35,14 +36,13 @@ def get_included_fields(model):
return False
-
FIELD_TO_FILTER = {
"ForeignKey": "MultipleChoiceFilter",
"ManyToManyField": "MultipleChoiceFilter",
"TextField": "CharFilter",
"CharField": "CharFilter",
"DateField": "DateFromToRangeFilter",
- "BooleanField": "BooleanFilter"
+ "BooleanField": "BooleanFilter",
}
@@ -50,11 +50,12 @@ def get_field_dicts(model, include_parents=False):
fields = [
{
"f_name": x.name,
- "f_v_name": getattr(x, 'verbose_name', None),
- "f_help_text": getattr(x, 'helptext', None),
+ "f_v_name": getattr(x, "verbose_name", None),
+ "f_help_text": getattr(x, "helptext", None),
"f_class_name": "{}".format(x.__class__.__name__),
- "f_model": getattr(x, 'related_model', None)
- } for x in model._meta.get_fields(include_parents=include_parents)
+ "f_model": getattr(x, "related_model", None),
+ }
+ for x in model._meta.get_fields(include_parents=include_parents)
]
return fields
@@ -63,14 +64,14 @@ def get_filters(model, exclude=False, include=False, include_parents=False):
filters = []
field_dicts = get_field_dicts(model, include_parents=include_parents)
for x in field_dicts:
- filters.append(x['f_name'])
- if x['f_model']:
- rel_fields = get_field_dicts(x['f_model'], include_parents)
+ filters.append(x["f_name"])
+ if x["f_model"]:
+ rel_fields = get_field_dicts(x["f_model"], include_parents)
for y in rel_fields:
- if 'apis_relations' in "{}".format(y['f_model']):
+ if "apis_relations" in "{}".format(y["f_model"]):
pass
else:
- rel_field_name = "{}__{}".format(x['f_name'], y['f_name'])
+ rel_field_name = "{}__{}".format(x["f_name"], y["f_name"])
filters.append(rel_field_name)
if include:
filters = [x for x in filters if x in include]
@@ -81,7 +82,9 @@ def get_filters(model, exclude=False, include=False, include_parents=False):
elif x.startswith("*") and x.endswith("*"):
filters = [f for f in filters if not x[1:-1].lower() in f]
elif not x.startswith("*") and x.endswith("*"):
- filters = [f for f in filters if not f.lower().startswith(x[:-1].lower())]
+ filters = [
+ f for f in filters if not f.lower().startswith(x[:-1].lower())
+ ]
else:
filters = [f for f in filters if not x.lower() == f.lower()]
return filters
@@ -89,7 +92,7 @@ def get_filters(model, exclude=False, include=False, include_parents=False):
def get_generic_relation_filter(entity):
class GenericListFilter(django_filters.FilterSet):
- #search = django_filters.CharFilter(method='search_filter_method')
+ # search = django_filters.CharFilter(method='search_filter_method')
def name_label_filter(self, queryset, name, value):
"""
@@ -102,50 +105,54 @@ def name_label_filter(self, queryset, name, value):
:param value: value for the filter
:return: filtered queryset
"""
- alternate_names = getattr(settings, "APIS_ALTERNATE_NAMES", ['alternative name'])
+ alternate_names = getattr(
+ settings, "APIS_ALTERNATE_NAMES", ["alternative name"]
+ )
res = []
orig_value = value
- for n in ['name', 'label__label']:
+ for n in ["name", "label__label"]:
value = orig_value
- f = '{}__'.format(n)
+ f = "{}__".format(n)
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
else:
- f += 'i'
- if value.startswith('*') and value.endswith('*'):
- f += 'contains'
+ f += "i"
+ if value.startswith("*") and value.endswith("*"):
+ f += "contains"
value = value[1:-1]
- elif value.startswith('*'):
- f += 'endswith'
+ elif value.startswith("*"):
+ f += "endswith"
value = value[1:]
- elif value.endswith('*'):
- f += 'startswith'
+ elif value.endswith("*"):
+ f += "startswith"
value = value[:-1]
else:
- f += 'exact'
- if n == 'label__label':
- res.append(Q(**{f: value, 'label__label_type__name__in': alternate_names}))
+ f += "exact"
+ if n == "label__label":
+ res.append(
+ Q(**{f: value, "label__label_type__name__in": alternate_names})
+ )
else:
res.append(Q(**{f: value}))
return queryset.filter(res[0] | res[1]).distinct()
def wildcard_filter(self, queryset, name, value):
- f = '{}__'.format(name)
+ f = "{}__".format(name)
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
else:
- f += 'i'
- if value.startswith('*') and value.endswith('*'):
- f += 'contains'
+ f += "i"
+ if value.startswith("*") and value.endswith("*"):
+ f += "contains"
value = value[1:-1]
- elif value.startswith('*'):
- f += 'endswith'
+ elif value.startswith("*"):
+ f += "endswith"
value = value[1:]
- elif value.endswith('*'):
- f += 'startswith'
+ elif value.endswith("*"):
+ f += "startswith"
value = value[:-1]
else:
- f += 'exact'
+ f += "exact"
return queryset.filter(**{f: value})
def search_filter_method(self, queryset, name, value):
@@ -153,8 +160,9 @@ def search_filter_method(self, queryset, name, value):
sett_filters = getattr(settings, "APIS_RELATIONS", {})
if cls.lower() in sett_filters.keys():
filter_attr = sett_filters[cls.lower()].get("search", ["name"])
- query = reduce(operator.or_, [ Q(**{attr: value}) for attr in filter_attr ] )
-
+ query = reduce(
+ operator.or_, [Q(**{attr: value}) for attr in filter_attr]
+ )
class Meta:
model = AbstractRelation.get_relation_class_of_name(entity)
@@ -162,50 +170,66 @@ class Meta:
model,
exclude=get_excluded_fields(model),
include=get_included_fields(model),
- include_parents=True
+ include_parents=True,
)
-
if "apis_ampel" in settings.INSTALLED_APPS:
from apis_ampel.models import AmpelTemp
- ampel = django_filters.ChoiceFilter(choices=AmpelTemp.ampel_choices, field_name="ampel__status", label="Ampel", null_label="default")
-
+ ampel = django_filters.ChoiceFilter(
+ choices=AmpelTemp.ampel_choices,
+ field_name="ampel__status",
+ label="Ampel",
+ null_label="default",
+ )
+
def __init__(self, *args, **kwargs):
- attrs = {'data-placeholder': 'Type to get suggestions',
- 'data-minimum-input-length': getattr(settings, "APIS_MIN_CHAR", 3),
- 'data-html': True}
+ attrs = {
+ "data-placeholder": "Type to get suggestions",
+ "data-minimum-input-length": getattr(settings, "APIS_MIN_CHAR", 3),
+ "data-html": True,
+ }
super(GenericListFilter, self).__init__(*args, **kwargs)
for x in self.filters.keys():
if type(self.filters[x].field).__name__ == "ModelChoiceField":
- current_model_name = str(self.filters[x].queryset.model.__name__).lower()
+ current_model_name = str(
+ self.filters[x].queryset.model.__name__
+ ).lower()
current_qs = self.filters[x].queryset
- if ContentType.objects.filter(app_label='apis_entities', model=current_model_name).count() > 0:
+ if (
+ ContentType.objects.filter(
+ app_label="apis_entities", model=current_model_name
+ ).count()
+ > 0
+ ):
self.filters[x] = django_filters.ModelMultipleChoiceFilter(
field_name=x,
queryset=current_qs,
widget=autocomplete.ModelSelect2Multiple(
url=reverse(
- 'apis:apis_entities:generic_network_entities_autocomplete',
- kwargs={
- 'entity': current_model_name
- }
+ "apis:apis_entities:generic_network_entities_autocomplete",
+ kwargs={"entity": current_model_name},
),
- )
+ ),
)
- elif ContentType.objects.filter(app_label='apis_vocabularies', model=current_model_name).count() > 0:
+ elif (
+ ContentType.objects.filter(
+ app_label="apis_vocabularies", model=current_model_name
+ ).count()
+ > 0
+ ):
self.filters[x] = django_filters.ModelMultipleChoiceFilter(
field_name=x,
queryset=current_qs,
widget=autocomplete.ModelSelect2Multiple(
url=reverse(
- 'apis:apis_vocabularies:generic_vocabularies_autocomplete',
+ "apis:apis_vocabularies:generic_vocabularies_autocomplete",
kwargs={
- 'vocab': current_model_name,
- 'direct': 'normal'
- }
+ "vocab": current_model_name,
+ "direct": "normal",
+ },
),
- )
+ ),
)
if type(self.filters[x].field).__name__ == "DateField":
self.filters[x] = django_filters.DateFromToRangeFilter(
@@ -213,22 +237,23 @@ def __init__(self, *args, **kwargs):
)
if type(self.filters[x].field).__name__ == "CharField":
self.filters[x] = django_filters.CharFilter(
- lookup_expr='icontains',
+ lookup_expr="icontains",
field_name=x,
)
if type(self.filters[x].field).__name__ == "ModelMultipleChoiceField":
- current_model_name = str(self.filters[x].queryset.model.__name__).lower()
+ current_model_name = str(
+ self.filters[x].queryset.model.__name__
+ ).lower()
current_qs = self.filters[x].queryset
self.filters[x] = django_filters.ModelMultipleChoiceFilter(
field_name=x,
queryset=current_qs,
widget=autocomplete.ModelSelect2Multiple(
url=reverse(
- 'apis:apis_entities:generic_network_entities_autocomplete',
- kwargs={
- 'entity': current_model_name
- }
+ "apis:apis_entities:generic_network_entities_autocomplete",
+ kwargs={"entity": current_model_name},
),
- )
+ ),
)
+
return GenericListFilter
diff --git a/apis_core/apis_relations/rel_views.py b/apis_core/apis_relations/rel_views.py
index f4c8834..c0953b4 100644
--- a/apis_core/apis_relations/rel_views.py
+++ b/apis_core/apis_relations/rel_views.py
@@ -10,33 +10,34 @@
class GenericRelationView(GenericListViewNew):
- context_filter_name = 'filter'
+ context_filter_name = "filter"
paginate_by = 25
template_name = getattr(
- settings,
- 'APIS_LIST_VIEW_TEMPLATE',
- 'apis_entities/generic_list.html'
+ settings, "APIS_LIST_VIEW_TEMPLATE", "apis_entities/generic_list.html"
)
- #login_url = '/accounts/login/'
+ # login_url = '/accounts/login/'
def get_queryset(self, **kwargs):
- self.entity = self.kwargs.get('entity')
+ self.entity = self.kwargs.get("entity")
qs = AbstractRelation.get_relation_class_of_name(self.entity).objects.all()
- self.filter = get_generic_relation_filter(
- self.entity.title())(self.request.GET, queryset=qs)
+ self.filter = get_generic_relation_filter(self.entity.title())(
+ self.request.GET, queryset=qs
+ )
self.filter.form.helper = self.formhelper_class()
- if callable(getattr(self.filter.qs, 'filter_for_user', None)):
+ if callable(getattr(self.filter.qs, "filter_for_user", None)):
return self.filter.qs.filter_for_user().distinct()
else:
return self.filter.qs.distinct()
-
def get_table(self, **kwargs):
- relation_name = self.kwargs['entity'].lower()
- self.table_class = get_generic_relation_listview_table(relation_name=relation_name)
+ relation_name = self.kwargs["entity"].lower()
+ self.table_class = get_generic_relation_listview_table(
+ relation_name=relation_name
+ )
table = super(GenericListViewNew, self).get_table()
- RequestConfig(self.request, paginate={
- 'page': 1, 'per_page': self.paginate_by}).configure(table)
+ RequestConfig(
+ self.request, paginate={"page": 1, "per_page": self.paginate_by}
+ ).configure(table)
return table
@@ -44,19 +45,19 @@ class GenericRelationDetailView(DetailView):
template_name = getattr(
settings,
- 'APIS_RELATIONS_DETAIL_VIEW_TEMPLATE',
- 'apis_relations/relations_detail_generic.html'
+ "APIS_RELATIONS_DETAIL_VIEW_TEMPLATE",
+ "apis_relations/relations_detail_generic.html",
)
def get_object(self):
- entity = self.kwargs['entity'].lower()
- instance = self.kwargs['pk'].lower()
+ entity = self.kwargs["entity"].lower()
+ instance = self.kwargs["pk"].lower()
entity_model = AbstractRelation.get_relation_class_of_name(entity)
instance = entity_model.objects.get(pk=instance)
return instance
def get_context_data(self, **kwargs):
context = super(GenericRelationDetailView, self).get_context_data()
- context['entity'] = self.kwargs['entity'].lower()
- context['entity_type'] = context['entity']
+ context["entity"] = self.kwargs["entity"].lower()
+ context["entity_type"] = context["entity"]
return context
diff --git a/apis_core/apis_relations/serializers.py b/apis_core/apis_relations/serializers.py
index dff5038..243201d 100644
--- a/apis_core/apis_relations/serializers.py
+++ b/apis_core/apis_relations/serializers.py
@@ -1,28 +1,37 @@
from rest_framework import serializers
-from apis_core.apis_entities.serializers import (
- PersonSerializer,
- PlaceSerializer
-)
+from apis_core.apis_entities.serializers import PersonSerializer, PlaceSerializer
from apis_core.apis_vocabularies.serializers import (
PersonPlaceRelationSerializer,
)
-from .models import (InstitutionInstitution, PersonInstitution, PersonPlace, PersonPerson,
- PersonEvent, PersonWork, InstitutionPlace, InstitutionEvent, InstitutionWork,
- PlaceEvent, PlaceWork, PlacePlace, EventWork, EventEvent, WorkWork)
+from .models import (
+ InstitutionInstitution,
+ PersonInstitution,
+ PersonPlace,
+ PersonPerson,
+ PersonEvent,
+ PersonWork,
+ InstitutionPlace,
+ InstitutionEvent,
+ InstitutionWork,
+ PlaceEvent,
+ PlaceWork,
+ PlacePlace,
+ EventWork,
+ EventEvent,
+ WorkWork,
+)
class InstitutionInstitutionSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionInstitution
class PersonInstitutionSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonInstitution
@@ -33,8 +42,7 @@ class PersonPlaceSerializer(serializers.HyperlinkedModelSerializer):
# lookup_field="pk"
# )
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:personplace-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:personplace-detail", lookup_field="pk"
)
related_person = PersonSerializer()
related_place = PlaceSerializer()
@@ -43,102 +51,90 @@ class PersonPlaceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
fields = [
- 'url',
- 'id',
- 'related_person',
- 'related_place',
- 'start_date',
- 'start_date_written',
- 'end_date',
- 'end_date_written',
- 'relation_type',
+ "url",
+ "id",
+ "related_person",
+ "related_place",
+ "start_date",
+ "start_date_written",
+ "end_date",
+ "end_date_written",
+ "relation_type",
]
model = PersonPlace
class PersonPersonSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonPerson
class PersonEventSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonEvent
class PersonWorkSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonWork
class InstitutionPlaceSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:institutionplace-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:institutionplace-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionPlace
class InstitutionEventSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionEvent
class InstitutionWorkSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionWork
class PlaceEventSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlaceEvent
class PlaceWorkSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlaceWork
class PlacePlaceSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlacePlace
class EventWorkSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = EventWork
class EventEventSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = EventEvent
class WorkWorkSerializer(serializers.HyperlinkedModelSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = WorkWork
diff --git a/apis_core/apis_relations/tables.py b/apis_core/apis_relations/tables.py
index 791cac6..15f7bfb 100644
--- a/apis_core/apis_relations/tables.py
+++ b/apis_core/apis_relations/tables.py
@@ -9,11 +9,11 @@
generic_order_start_date_written,
generic_order_end_date_written,
generic_render_start_date_written,
- generic_render_end_date_written
+ generic_render_end_date_written,
)
from apis_core.apis_relations.models import AbstractRelation
-empty_text_default = 'There are currently no relations'
+empty_text_default = "There are currently no relations"
def get_generic_relation_listview_table(relation_name):
@@ -25,13 +25,16 @@ def get_generic_relation_listview_table(relation_name):
:return: a django-tables2 Table Class tailored for the respective relation class
"""
-
# create all variables which save the foreign key fields which are different for each relation class
relation_class = AbstractRelation.get_relation_class_of_name(relation_name)
- related_entity_class_name_a = relation_class.get_related_entity_classA().__name__.lower()
- related_entity_class_name_b = relation_class.get_related_entity_classB().__name__.lower()
- related_entity_field_name_a = relation_class.get_related_entity_field_nameA()
- related_entity_field_name_b = relation_class.get_related_entity_field_nameB()
+ related_entity_class_name_a = (
+ relation_class.get_related_entity_classa().__name__.lower()
+ )
+ related_entity_class_name_b = (
+ relation_class.get_related_entity_classb().__name__.lower()
+ )
+ related_entity_field_name_a = relation_class.get_related_entity_field_namea()
+ related_entity_field_name_b = relation_class.get_related_entity_field_nameb()
class GenericRelationListViewTable(tables.Table):
@@ -43,7 +46,6 @@ class GenericRelationListViewTable(tables.Table):
render_start_date_written = generic_render_start_date_written
render_end_date_written = generic_render_end_date_written
-
class Meta:
model = relation_class
@@ -51,9 +53,9 @@ class Meta:
fields = [
related_entity_field_name_a,
related_entity_field_name_b,
- 'relation_type',
- 'start_date_written',
- 'end_date_written',
+ "relation_type",
+ "start_date_written",
+ "end_date_written",
]
# reuse the list for ordering
sequence = tuple(fields)
@@ -66,37 +68,29 @@ def __init__(self, *args, **kwargs):
# LinkColumn objects provied hyperlinking to the related entities
self.base_columns[related_entity_field_name_a] = tables.LinkColumn(
# which url to use:
- 'apis:apis_entities:generic_entities_detail_view',
+ "apis:apis_entities:generic_entities_detail_view",
args=[
# which entity sub-url to load from:
related_entity_class_name_a,
# which instance identifier to use:
- A(related_entity_field_name_a + ".pk")
- ]
+ A(related_entity_field_name_a + ".pk"),
+ ],
)
# same as above
self.base_columns[related_entity_field_name_b] = tables.LinkColumn(
- 'apis:apis_entities:generic_entities_detail_view',
+ "apis:apis_entities:generic_entities_detail_view",
args=[
related_entity_class_name_b,
- A(related_entity_field_name_b + ".pk")
- ]
+ A(related_entity_field_name_b + ".pk"),
+ ],
)
- if "apis_ampel" in settings.INSTALLED_APPS:
- from apis_ampel.helper_functions import is_ampel_active
- if is_ampel_active(relation_name):
- self.base_columns['ampel'] = tables.TemplateColumn(template_name = "ampel/ampel_template_column.html", verbose_name="Ampel")
-
-
super().__init__(*args, **kwargs)
-
return GenericRelationListViewTable
-
def get_generic_relations_table(relation_class, entity_instance, detail=None):
"""
Creates a table class according to the relation and entity class given by the parameters.
@@ -109,10 +103,14 @@ def get_generic_relations_table(relation_class, entity_instance, detail=None):
# create all variables which save the foreign key fields which are different for each relation class
entity_class_name = entity_instance.__class__.__name__.lower()
- related_entity_class_name_a = relation_class.get_related_entity_classA().__name__.lower()
- related_entity_class_name_b = relation_class.get_related_entity_classB().__name__.lower()
- related_entity_field_name_a = relation_class.get_related_entity_field_nameA()
- related_entity_field_name_b = relation_class.get_related_entity_field_nameB()
+ related_entity_class_name_a = (
+ relation_class.get_related_entity_classa().__name__.lower()
+ )
+ related_entity_class_name_b = (
+ relation_class.get_related_entity_classb().__name__.lower()
+ )
+ related_entity_field_name_a = relation_class.get_related_entity_field_namea()
+ related_entity_field_name_b = relation_class.get_related_entity_field_nameb()
# find out what other entity class the current entity instance in a given relation class is related to
# (needed for linkg towards instances of related entities)
@@ -127,11 +125,10 @@ def get_generic_relations_table(relation_class, entity_instance, detail=None):
else:
raise Exception(
- "Did not find the entity instance in the given relation class fields!" +
- "Either a wrong entity instance or wrong relation class was passed to this function."
+ "Did not find the entity instance in the given relation class fields!"
+ + "Either a wrong entity instance or wrong relation class was passed to this function."
)
-
class RelationTableBase(tables.Table):
"""
The base table from which detail or edit tables will inherit from in order to avoid redundant definitions
@@ -155,10 +152,10 @@ class Meta:
# the fields list also serves as the defining order of them, as to avoid duplicated definitions
fields = [
- 'start_date_written',
- 'end_date_written',
- 'other_relation_type',
- "other_related_entity"
+ "start_date_written",
+ "end_date_written",
+ "other_relation_type",
+ "other_related_entity",
]
# reuse the list for ordering
sequence = tuple(fields)
@@ -166,7 +163,9 @@ class Meta:
# This attrs dictionary I took over from the tables implementation before. No idea if and where it would be needed.
attrs = {
"class": "table table-hover table-striped table-condensed",
- "id": related_entity_class_name_a.title()[:2] + related_entity_class_name_b.title()[:2] + "_conn"
+ "id": related_entity_class_name_a.title()[:2]
+ + related_entity_class_name_b.title()[:2]
+ + "_conn",
}
def render_other_related_entity(self, record, value):
@@ -180,19 +179,18 @@ def render_other_related_entity(self, record, value):
:return: related instance
"""
- if value == record.get_related_entity_instanceA().pk :
- return record.get_related_entity_instanceA()
+ if value == record.get_related_entity_instancea().pk:
+ return record.get_related_entity_instancea()
- elif value == record.get_related_entity_instanceB().pk :
- return record.get_related_entity_instanceB()
+ elif value == record.get_related_entity_instanceb().pk:
+ return record.get_related_entity_instanceb()
else:
raise Exception(
- "Did not find the entity this relation is supposed to come from!" +
- "Something must have went wrong when annotating for the related instance."
+ "Did not find the entity this relation is supposed to come from!"
+ + "Something must have went wrong when annotating for the related instance."
)
-
def __init__(self, data, *args, **kwargs):
# annotations for displaying data about the 'other side' of the relation.
@@ -209,14 +207,18 @@ def __init__(self, data, *args, **kwargs):
# even in case two entities are of the same class.
other_related_entity=Case(
# **kwargs pattern is needed here as the key-value pairs change with each relation class and entity instance.
- When(**{
- related_entity_field_name_a + "__pk": entity_instance.pk,
- "then": related_entity_field_name_b
- }),
- When(**{
- related_entity_field_name_b + "__pk": entity_instance.pk,
- "then": related_entity_field_name_a
- }),
+ When(
+ **{
+ related_entity_field_name_a + "__pk": entity_instance.pk,
+ "then": related_entity_field_name_b,
+ }
+ ),
+ When(
+ **{
+ related_entity_field_name_b + "__pk": entity_instance.pk,
+ "then": related_entity_field_name_a,
+ }
+ ),
)
).annotate(
# Get the correct side of the relation type given the current entity instance.
@@ -225,28 +227,33 @@ def __init__(self, data, *args, **kwargs):
# guarantees that the other related entity is always correctly picked,
# even in case two entities are of the same class.
other_relation_type=Case(
- When(**{
- # A->B relation and current entity instance is A, hence take forward name
- related_entity_field_name_a + "__pk": entity_instance.pk,
- "then": "relation_type__name"
- }),
- When(**{
- # A->B relation and current entity instance is B, hence take reverse name.
- related_entity_field_name_b + "__pk": entity_instance.pk,
- "then": "relation_type__name_reverse"
- }),
- )
+ When(
+ **{
+ # A->B relation and current entity instance is A, hence take forward name
+ related_entity_field_name_a + "__pk": entity_instance.pk,
+ "then": "relation_type__name",
+ }
+ ),
+ When(
+ **{
+ # A->B relation and current entity instance is B, hence take reverse name.
+ related_entity_field_name_b + "__pk": entity_instance.pk,
+ "then": "relation_type__name_reverse",
+ }
+ ),
+ )
)
for an in data:
- if getattr(an, f"{related_entity_field_name_a}_id") == entity_instance.pk:
+ if (
+ getattr(an, f"{related_entity_field_name_a}_id")
+ == entity_instance.pk
+ ):
an.other_relation_type = getattr(an.relation_type, "label")
else:
an.other_relation_type = getattr(an.relation_type, "label_reverse")
-
super().__init__(data, *args, **kwargs)
-
if detail:
class RelationTableDetail(RelationTableBase):
@@ -259,30 +266,15 @@ def __init__(self, data, *args, **kwargs):
# Only addition with respect to parent class is which main url is to be used when clicking on a
# related entity column.
self.base_columns["other_related_entity"] = tables.LinkColumn(
- 'apis:apis_entities:generic_entities_detail_view',
- args=[
- other_related_entity_class_name,
- A("other_related_entity")
- ],
- verbose_name="Related " + other_related_entity_class_name.title()
+ "apis:apis_entities:generic_entities_detail_view",
+ args=[other_related_entity_class_name, A("other_related_entity")],
+ verbose_name="Related " + other_related_entity_class_name.title(),
)
- if "apis_ampel" in settings.INSTALLED_APPS:
- from apis_ampel.helper_functions import is_ampel_active
-
- if is_ampel_active(relation_class.__name__):
- self.base_columns['ampel'] = tables.TemplateColumn(template_name = "ampel/edit_inline_table_column.html", verbose_name="Ampel")
-
-
-
-
-
super().__init__(data=data, *args, **kwargs)
-
return RelationTableDetail
-
else:
class RelationTableEdit(RelationTableBase):
@@ -298,69 +290,49 @@ class Meta(RelationTableBase.Meta):
# This fields list also defines the order of the elements.
fields = ["delete"] + RelationTableBase.Meta.fields + ["edit"]
- if 'apis_bibsonomy' in settings.INSTALLED_APPS:
- fields = ["ref"] + fields
-
# again reuse the fields list for ordering
sequence = tuple(fields)
-
def __init__(self, *args, **kwargs):
# Clicking on a related entity will lead also the edit view of the related entity instance
self.base_columns["other_related_entity"] = tables.LinkColumn(
- 'apis:apis_entities:generic_entities_edit_view',
- args=[
- other_related_entity_class_name, A("other_related_entity")
- ],
- verbose_name="Related " + other_related_entity_class_name.title()
+ "apis:apis_entities:generic_entities_edit_view",
+ args=[other_related_entity_class_name, A("other_related_entity")],
+ verbose_name="Related " + other_related_entity_class_name.title(),
)
# delete button
- self.base_columns['delete'] = tables.TemplateColumn(
- template_name='apis_relations/delete_button_generic_ajax_form.html'
+ self.base_columns["delete"] = tables.TemplateColumn(
+ template_name="apis_relations/delete_button_generic_ajax_form.html"
)
# edit button
- self.base_columns['edit'] = tables.TemplateColumn(
- template_name='apis_relations/edit_button_generic_ajax_form.html'
+ self.base_columns["edit"] = tables.TemplateColumn(
+ template_name="apis_relations/edit_button_generic_ajax_form.html"
)
- # bibsonomy button
- if 'apis_bibsonomy' in settings.INSTALLED_APPS:
- self.base_columns['ref'] = tables.TemplateColumn(
- template_name='apis_relations/references_button_generic_ajax_form.html'
- )
-
- # __g.pirgie__ deactivated for now as it broke ajax forms
- # if "apis_ampel" in settings.INSTALLED_APPS:
- # from apis_ampel.helper_functions import is_ampel_active
-
- # if is_ampel_active(relation_class.__name__):
- # self.base_columns['ampel'] = tables.TemplateColumn(template_name = "ampel/ampel_edit_template_column.html", verbose_name="Ampel")
-
-
-
super().__init__(*args, **kwargs)
-
return RelationTableEdit
-
class EntityUriTable(tables.Table):
- delete = tables.TemplateColumn(template_name='apis_relations/delete_button_Uri_ajax_form.html')
+ delete = tables.TemplateColumn(
+ template_name="apis_relations/delete_button_Uri_ajax_form.html"
+ )
class Meta:
empty_text = empty_text_default
model = Uri
- fields = ['uri']
- sequence = ('delete', 'uri')
+ fields = ["uri"]
+ sequence = ("delete", "uri")
# add class="paleblue" to
tag
- attrs = {"class": "table table-hover table-striped table-condensed",
- "id": "PURI_conn"}
-
+ attrs = {
+ "class": "table table-hover table-striped table-condensed",
+ "id": "PURI_conn",
+ }
class LabelTableBase(tables.Table):
@@ -382,31 +354,45 @@ class Meta:
# Note that as the next attribute 'sequence' builds on this list 'fields', the order defined within this list
# will be reused for the tuple 'sequence'. So if the order needs to be changed, better do it here in the list 'fields'.
- fields = ['start_date_written', 'end_date_written', 'label_type', 'isoCode_639_3']
- sequence = ('label',) + tuple(fields)
+ fields = [
+ "start_date_written",
+ "end_date_written",
+ "label_type",
+ "isocode_639_3",
+ ]
+ sequence = ("label",) + tuple(fields)
# add class="paleblue" to
tag
attrs = {
"class": "table table-hover table-striped table-condensed",
"id": "PL_conn",
- "style": "table-layout: fixed;"
+ "style": "table-layout: fixed;",
}
-
+
def __init__(self, **kwargs):
- self.base_columns["start_date_written"].attrs = {"th": {"class": "d-none d-lg-table-cell"},"td": {"class": "d-none d-lg-table-cell"}}
- self.base_columns["end_date_written"].attrs = {"th": {"class": "d-none d-lg-table-cell"},"td": {"class": "d-none d-lg-table-cell"}}
- self.base_columns["isoCode_639_3"].attrs = {"th": {"class": "d-none d-lg-table-cell"},"td": {"class": "d-none d-lg-table-cell"}}
+ self.base_columns["start_date_written"].attrs = {
+ "th": {"class": "d-none d-lg-table-cell"},
+ "td": {"class": "d-none d-lg-table-cell"},
+ }
+ self.base_columns["end_date_written"].attrs = {
+ "th": {"class": "d-none d-lg-table-cell"},
+ "td": {"class": "d-none d-lg-table-cell"},
+ }
+ self.base_columns["isocode_639_3"].attrs = {
+ "th": {"class": "d-none d-lg-table-cell"},
+ "td": {"class": "d-none d-lg-table-cell"},
+ }
super().__init__(**kwargs)
-
class LabelTableEdit(LabelTableBase):
"""
Reuse most of the base table class for labels. Only addition is editing functionality.
"""
- edit = tables.TemplateColumn(template_name='apis_relations/edit_button_persLabel_ajax_form.html')
+ edit = tables.TemplateColumn(
+ template_name="apis_relations/edit_button_persLabel_ajax_form.html"
+ )
class Meta(LabelTableBase.Meta):
sequence = LabelTableBase.Meta.sequence + ("edit",)
-
diff --git a/apis_core/apis_relations/templatetags/apis_helpers.py b/apis_core/apis_relations/templatetags/apis_helpers.py
index 0400226..27e7a4b 100644
--- a/apis_core/apis_relations/templatetags/apis_helpers.py
+++ b/apis_core/apis_relations/templatetags/apis_helpers.py
@@ -3,14 +3,15 @@
register = template.Library()
+
@register.filter
def content_type(obj):
if not obj:
return False
if type(obj) == dict:
for x in obj.keys():
- if x.startswith('related_'):
- nl = [x.split('_')[1], x.split('_')[1]]
+ if x.startswith("related_"):
+ nl = [x.split("_")[1], x.split("_")[1]]
else:
nl = ContentType.objects.get_for_model(obj).name.split()
- return ''.join([x.title() for x in nl])
+ return "".join([x.title() for x in nl])
diff --git a/apis_core/apis_relations/urls.py b/apis_core/apis_relations/urls.py
index b887770..c1b8a8c 100644
--- a/apis_core/apis_relations/urls.py
+++ b/apis_core/apis_relations/urls.py
@@ -7,15 +7,18 @@
urlpatterns = [
path("ajax/get/", views.get_form_ajax, name="get_form_ajax"),
- path("ajax/save/////",
+ path(
+ "ajax/save/////",
views.save_ajax_form,
name="save_ajax_form",
),
- path("/list/",
+ path(
+ "/list/",
rel_views.GenericRelationView.as_view(),
name="generic_relations_list",
),
- path("//detail",
+ path(
+ "//detail",
rel_views.GenericRelationDetailView.as_view(),
name="generic_relations_detail_view",
),
diff --git a/apis_core/apis_relations/views.py b/apis_core/apis_relations/views.py
index 92c34b3..8e7bba0 100644
--- a/apis_core/apis_relations/views.py
+++ b/apis_core/apis_relations/views.py
@@ -9,23 +9,43 @@
from django.template.loader import render_to_string
from apis_core.apis_relations import forms as relation_form_module
-from apis_core.apis_entities.models import Person, Institution, Place, Event, Work, AbstractEntity
+from apis_core.apis_entities.models import (
+ Person,
+ Institution,
+ Place,
+ Event,
+ Work,
+ AbstractEntity,
+)
from apis_core.apis_labels.models import Label
from apis_core.apis_metainfo.models import Uri
from .forms2 import GenericRelationForm
from .models import (
- PersonPlace, PersonPerson, PersonInstitution, InstitutionPlace,
- InstitutionInstitution, PlacePlace, PersonEvent, InstitutionEvent, PlaceEvent, PersonWork,
- InstitutionWork, PlaceWork, EventWork, WorkWork
+ PersonPlace,
+ PersonPerson,
+ PersonInstitution,
+ InstitutionPlace,
+ InstitutionInstitution,
+ PlacePlace,
+ PersonEvent,
+ InstitutionEvent,
+ PlaceEvent,
+ PersonWork,
+ InstitutionWork,
+ PlaceWork,
+ EventWork,
+ WorkWork,
)
-#from .forms import PersonLabelForm, InstitutionLabelForm, PlaceLabelForm, EventLabelForm
+
+# from .forms import PersonLabelForm, InstitutionLabelForm, PlaceLabelForm, EventLabelForm
from .tables import LabelTableEdit
form_module_list = [relation_form_module]
-if 'apis_highlighter' in settings.INSTALLED_APPS:
+if "apis_highlighter" in settings.INSTALLED_APPS:
from apis_highlighter.highlighter import highlight_text_new
from apis_highlighter import forms as highlighter_form_module
+
form_module_list.append(highlighter_form_module)
@@ -43,6 +63,7 @@ def turn_form_modules_into_dict(form_module_list):
return form_class_dict
+
form_class_dict = turn_form_modules_into_dict(form_module_list)
@@ -60,142 +81,150 @@ def turn_form_modules_into_dict(form_module_list):
# Model-classes must be registered together with their ModelForm-classes
-registered_forms = {'WorkWorkForm': [WorkWork, Work, Work],
- 'PersonPlaceForm': [PersonPlace, Person, Place],
- 'PersonPlaceHighlighterForm': [PersonPlace, Person, Place],
- 'PersonPersonForm': [PersonPerson, Person, Person],
- 'PersonPersonHighlighterForm': [PersonPerson, Person, Person],
- 'PersonInstitutionForm': [PersonInstitution, Person, Institution],
- 'PersonEventForm': [PersonEvent, Person, Event],
- 'PersonWorkForm': [PersonWork, Person, Work],
- 'PersonInstitutionHighlighterForm': [PersonInstitution, Person, Institution],
- 'PersonWorkHighlighterForm': [PersonWork, Person, Work],
- 'PlaceWorkHighlighterForm': [PlaceWork, Place, Work],
- 'InstitutionWorkHighlighterForm': [InstitutionWork, Institution, Work],
- 'InstitutionPlaceForm': [InstitutionPlace, Institution, Place],
- 'InstitutionInstitutionForm': [
- InstitutionInstitution,
- Institution,
- Institution],
- 'InstitutionPersonForm': [PersonInstitution, Institution, Person],
- 'InstitutionEventForm': [InstitutionEvent, Institution, Event],
- 'InstitutionWorkForm': [InstitutionWork, Institution, Work],
- 'PlaceEventForm': [PlaceEvent, Place, Event],
- 'PlaceWorkForm': [PlaceWork, Place, Work],
- 'PlacePlaceForm': [PlacePlace, Place, Place],
- 'EventWorkForm': [EventWork, Event, Work],
- 'InstitutionLabelForm': [Label, Institution, Label],
- 'PersonLabelForm': [Label, Person, Label],
- 'EventLabelForm': [Label, Event, Label],
- 'PersonResolveUriForm': [Uri, Person, Uri],
- 'SundayHighlighterForm': [ ],
- 'AddRelationHighlighterPersonForm': [],
- #'PlaceHighlighterForm': [Annotation, ],
- #'PersonHighlighterForm': [Annotation, ]
- }
+registered_forms = {
+ "WorkWorkForm": [WorkWork, Work, Work],
+ "PersonPlaceForm": [PersonPlace, Person, Place],
+ "PersonPlaceHighlighterForm": [PersonPlace, Person, Place],
+ "PersonPersonForm": [PersonPerson, Person, Person],
+ "PersonPersonHighlighterForm": [PersonPerson, Person, Person],
+ "PersonInstitutionForm": [PersonInstitution, Person, Institution],
+ "PersonEventForm": [PersonEvent, Person, Event],
+ "PersonWorkForm": [PersonWork, Person, Work],
+ "PersonInstitutionHighlighterForm": [PersonInstitution, Person, Institution],
+ "PersonWorkHighlighterForm": [PersonWork, Person, Work],
+ "PlaceWorkHighlighterForm": [PlaceWork, Place, Work],
+ "InstitutionWorkHighlighterForm": [InstitutionWork, Institution, Work],
+ "InstitutionPlaceForm": [InstitutionPlace, Institution, Place],
+ "InstitutionInstitutionForm": [InstitutionInstitution, Institution, Institution],
+ "InstitutionPersonForm": [PersonInstitution, Institution, Person],
+ "InstitutionEventForm": [InstitutionEvent, Institution, Event],
+ "InstitutionWorkForm": [InstitutionWork, Institution, Work],
+ "PlaceEventForm": [PlaceEvent, Place, Event],
+ "PlaceWorkForm": [PlaceWork, Place, Work],
+ "PlacePlaceForm": [PlacePlace, Place, Place],
+ "EventWorkForm": [EventWork, Event, Work],
+ "InstitutionLabelForm": [Label, Institution, Label],
+ "PersonLabelForm": [Label, Person, Label],
+ "EventLabelForm": [Label, Event, Label],
+ "PersonResolveUriForm": [Uri, Person, Uri],
+ "SundayHighlighterForm": [],
+ "AddRelationHighlighterPersonForm": [],
+ #'PlaceHighlighterForm': [Annotation, ],
+ #'PersonHighlighterForm': [Annotation, ]
+}
@login_required
def get_form_ajax(request):
- '''Returns forms rendered in html'''
+ """Returns forms rendered in html"""
- FormName = request.POST.get('FormName')
- SiteID = request.POST.get('SiteID')
- ButtonText = request.POST.get('ButtonText')
- ObjectID = request.POST.get('ObjectID')
- entity_type_str = request.POST.get('entity_type')
- form_match = re.match(r'([A-Z][a-z]+)([A-Z][a-z]+)(Highlighter)?Form', FormName)
- form_match2 = re.match(r'([A-Z][a-z]+)(Highlighter)?Form', FormName)
+ FormName = request.POST.get("FormName")
+ SiteID = request.POST.get("SiteID")
+ ButtonText = request.POST.get("ButtonText")
+ ObjectID = request.POST.get("ObjectID")
+ entity_type_str = request.POST.get("entity_type")
+ form_match = re.match(r"([A-Z][a-z]+)([A-Z][a-z]+)(Highlighter)?Form", FormName)
+ form_match2 = re.match(r"([A-Z][a-z]+)(Highlighter)?Form", FormName)
if FormName and form_match:
entity_type_v1 = ContentType.objects.filter(
- model='{}{}'.format(form_match.group(1).lower(), form_match.group(2)).lower(),
- app_label='apis_relations')
+ model="{}{}".format(
+ form_match.group(1).lower(), form_match.group(2)
+ ).lower(),
+ app_label="apis_relations",
+ )
entity_type_v2 = ContentType.objects.none()
elif FormName and form_match2:
entity_type_v2 = ContentType.objects.filter(
- model='{}'.format(
- form_match.group(1).lower(),
- app_label='apis_entities'))
+ model="{}".format(form_match.group(1).lower(), app_label="apis_entities")
+ )
entity_type_v1 = ContentType.objects.none()
else:
entity_type_v1 = ContentType.objects.none()
entity_type_v2 = ContentType.objects.none()
- if ObjectID == 'false' or ObjectID is None or ObjectID == 'None':
+ if ObjectID == "false" or ObjectID is None or ObjectID == "None":
ObjectID = False
- form_dict = {'entity_type': entity_type_str}
+ form_dict = {"entity_type": entity_type_str}
elif entity_type_v1.count() > 0:
d = entity_type_v1[0].model_class().objects.get(pk=ObjectID)
- form_dict = {'instance': d, 'siteID': SiteID, 'entity_type': entity_type_str}
+ form_dict = {"instance": d, "siteID": SiteID, "entity_type": entity_type_str}
elif entity_type_v2.count() > 0:
d = entity_type_v2[0].model_class().objects.get(pk=ObjectID)
- form_dict = {'instance': d, 'siteID': SiteID, 'entity_type': entity_type_str}
+ form_dict = {"instance": d, "siteID": SiteID, "entity_type": entity_type_str}
else:
if FormName not in registered_forms.keys():
raise Http404
d = registered_forms[FormName][0].objects.get(pk=ObjectID)
- form_dict = {'instance': d, 'siteID': SiteID, 'entity_type': entity_type_str}
+ form_dict = {"instance": d, "siteID": SiteID, "entity_type": entity_type_str}
if entity_type_v1.count() > 0:
- form_dict['relation_form'] = '{}{}'.format(form_match.group(1), form_match.group(2))
- if form_match.group(3) == 'Highlighter':
- form_dict['highlighter'] = True
+ form_dict["relation_form"] = "{}{}".format(
+ form_match.group(1), form_match.group(2)
+ )
+ if form_match.group(3) == "Highlighter":
+ form_dict["highlighter"] = True
form = GenericRelationForm(**form_dict)
else:
form_class = form_class_dict[FormName]
form = form_class(**form_dict)
tab = FormName[:-4]
- data = {'tab': tab, 'form': render_to_string("apis_relations/_ajax_form.html", {
+ data = {
+ "tab": tab,
+ "form": render_to_string(
+ "apis_relations/_ajax_form.html",
+ {
"entity_type": entity_type_str,
"form": form,
- 'type1': FormName,
- 'url2': 'save_ajax_'+FormName,
- 'button_text': ButtonText,
- 'ObjectID': ObjectID,
- 'SiteID': SiteID})}
+ "type1": FormName,
+ "url2": "save_ajax_" + FormName,
+ "button_text": ButtonText,
+ "ObjectID": ObjectID,
+ "SiteID": SiteID,
+ },
+ ),
+ }
- return HttpResponse(json.dumps(data), content_type='application/json')
+ return HttpResponse(json.dumps(data), content_type="application/json")
@login_required
def save_ajax_form(request, entity_type, kind_form, SiteID, ObjectID=False):
- '''Tests validity and saves AjaxForms, returns them when validity test fails'''
+ """Tests validity and saves AjaxForms, returns them when validity test fails"""
if kind_form not in registered_forms.keys():
raise Http404
button_text = "create/modify"
if not ObjectID:
- instance_id = ''
+ instance_id = ""
else:
instance_id = ObjectID
entity_type_str = entity_type
entity_type = AbstractEntity.get_entity_class_of_name(entity_type)
- form_match = re.match(r'([A-Z][a-z]+)([A-Z][a-z]+)?(Highlighter)?Form', kind_form)
- form_dict = {'data': request.POST,
- 'entity_type': entity_type,
- 'request': request}
+ form_match = re.match(r"([A-Z][a-z]+)([A-Z][a-z]+)?(Highlighter)?Form", kind_form)
+ form_dict = {"data": request.POST, "entity_type": entity_type, "request": request}
test_form_relations = ContentType.objects.filter(
- model='{}{}'.format(form_match.group(1).lower(), form_match.group(2)).lower(),
- app_label='apis_relations')
- tab = re.match(r'(.*)Form', kind_form).group(1)
- call_function = 'EntityRelationForm_response'
+ model="{}{}".format(form_match.group(1).lower(), form_match.group(2)).lower(),
+ app_label="apis_relations",
+ )
+ tab = re.match(r"(.*)Form", kind_form).group(1)
+ call_function = "EntityRelationForm_response"
if test_form_relations.count() > 0:
relation_form = test_form_relations[0].model_class()
- form_dict['relation_form'] = relation_form
- if form_match.group(3) == 'Highlighter':
- form_dict['highlighter'] = True
- tab = form_match.group(1)+form_match.group(2)
- call_function = 'HighlForm_response'
+ form_dict["relation_form"] = relation_form
+ if form_match.group(3) == "Highlighter":
+ form_dict["highlighter"] = True
+ tab = form_match.group(1) + form_match.group(2)
+ call_function = "HighlForm_response"
form = GenericRelationForm(**form_dict)
else:
form_class = form_class_dict[kind_form]
form = form_class(**form_dict)
if form.is_valid():
site_instance = entity_type.objects.get(pk=SiteID)
- set_ann_proj = request.session.get('annotation_project', 1)
- entity_types_highlighter = request.session.get('entity_types_highlighter')
- users_show = request.session.get('users_show_highlighter', None)
+ set_ann_proj = request.session.get("annotation_project", 1)
+ entity_types_highlighter = request.session.get("entity_types_highlighter")
+ users_show = request.session.get("users_show_highlighter", None)
hl_text = None
if ObjectID:
instance = form.save(instance=ObjectID, site_instance=site_instance)
@@ -203,32 +232,41 @@ def save_ajax_form(request, entity_type, kind_form, SiteID, ObjectID=False):
instance = form.save(site_instance=site_instance)
right_card = True
if test_form_relations.count() > 0:
- table_html = form.get_html_table(entity_type_str, request, site_instance, form_match)
- if 'Highlighter' in tab or form_match.group(3) == 'Highlighter':
+ table_html = form.get_html_table(
+ entity_type_str, request, site_instance, form_match
+ )
+ if "Highlighter" in tab or form_match.group(3) == "Highlighter":
hl_text = {
- 'text': highlight_text_new(form.get_text_id(),
- users_show=users_show,
- set_ann_proj=set_ann_proj,
- types=entity_types_highlighter)[0].strip(),
- 'id': form.get_text_id()}
- if tab == 'PersonLabel':
+ "text": highlight_text_new(
+ form.get_text_id(),
+ users_show=users_show,
+ set_ann_proj=set_ann_proj,
+ types=entity_types_highlighter,
+ )[0].strip(),
+ "id": form.get_text_id(),
+ }
+ if tab == "PersonLabel":
table_html = LabelTableEdit(
- data=site_instance.label_set.all(),
- prefix='PL-')
- elif tab == 'InstitutionLabel':
+ data=site_instance.label_set.all(), prefix="PL-"
+ )
+ elif tab == "InstitutionLabel":
table_html = LabelTableEdit(
- data=site_instance.label_set.all(),
- prefix='IL-')
- elif tab == 'PersonResolveUri':
+ data=site_instance.label_set.all(), prefix="IL-"
+ )
+ elif tab == "PersonResolveUri":
table_html = EntityUriTable(
- Uri.objects.filter(entity=site_instance),
- prefix='PURI-'
+ Uri.objects.filter(entity=site_instance), prefix="PURI-"
)
- elif tab == 'AddRelationHighlighterPerson' or tab == 'PlaceHighlighter' or tab == 'PersonHighlighter' or tab == 'SundayHighlighter':
+ elif (
+ tab == "AddRelationHighlighterPerson"
+ or tab == "PlaceHighlighter"
+ or tab == "PersonHighlighter"
+ or tab == "SundayHighlighter"
+ ):
table_html = None
right_card = False
- call_function = 'PAddRelation_response'
+ call_function = "PAddRelation_response"
instance = None
if instance:
instance2 = instance.get_web_object()
@@ -238,24 +276,39 @@ def save_ajax_form(request, entity_type, kind_form, SiteID, ObjectID=False):
table_html2 = table_html.as_html(request)
else:
table_html2 = None
- data = {'test': True, 'tab': tab, 'call_function': call_function,
- 'instance': instance2,
- 'table_html': table_html2,
- 'text': hl_text,
- 'right_card': right_card}
+ data = {
+ "test": True,
+ "tab": tab,
+ "call_function": call_function,
+ "instance": instance2,
+ "table_html": table_html2,
+ "text": hl_text,
+ "right_card": right_card,
+ }
else:
- if 'Highlighter' in tab:
- call_function = 'HighlForm_response'
- data = {'test': False, 'call_function': call_function,
- 'DivID': 'div_'+kind_form+instance_id,
- 'form': render_to_string("apis_relations/_ajax_form.html", context={
+ if "Highlighter" in tab:
+ call_function = "HighlForm_response"
+ data = {
+ "test": False,
+ "call_function": call_function,
+ "DivID": "div_" + kind_form + instance_id,
+ "form": render_to_string(
+ "apis_relations/_ajax_form.html",
+ context={
"entity_type": entity_type_str,
- "form": form, 'type1': kind_form, 'url2': 'save_ajax_'+kind_form,
- 'button_text': button_text, 'ObjectID': ObjectID, 'SiteID': SiteID},
- request=request)}
+ "form": form,
+ "type1": kind_form,
+ "url2": "save_ajax_" + kind_form,
+ "button_text": button_text,
+ "ObjectID": ObjectID,
+ "SiteID": SiteID,
+ },
+ request=request,
+ ),
+ }
# except Exception as e:
# print('Error in save method')
# print(e)
# data = {'test': False, 'error': json.dumps(str(e))}
- return HttpResponse(json.dumps(data), content_type='application/json')
+ return HttpResponse(json.dumps(data), content_type="application/json")
diff --git a/apis_core/apis_tei/apps.py b/apis_core/apis_tei/apps.py
index b0fe9a9..c6974de 100644
--- a/apis_core/apis_tei/apps.py
+++ b/apis_core/apis_tei/apps.py
@@ -2,4 +2,4 @@
class TeiConfig(AppConfig):
- name = 'apis_core.apis_tei'
+ name = "apis_core.apis_tei"
diff --git a/apis_core/apis_tei/management/commands/orgs_to_tei.py b/apis_core/apis_tei/management/commands/orgs_to_tei.py
index 4beaf76..6361653 100644
--- a/apis_core/apis_tei/management/commands/orgs_to_tei.py
+++ b/apis_core/apis_tei/management/commands/orgs_to_tei.py
@@ -5,58 +5,59 @@
from apis_core.apis_entities.models import Institution
from apis_core.apis_tei.tei_utils import get_node_from_template, tei_header
+
class Command(BaseCommand):
- help = 'Command to serialize APIS Institutions to XML/TEI places.xml'
+ help = "Command to serialize APIS Institutions to XML/TEI places.xml"
def add_arguments(self, parser):
parser.add_argument(
- '-l',
- '--limit',
- action='store_true',
- help='number of entities should be limited',
+ "-l",
+ "--limit",
+ action="store_true",
+ help="number of entities should be limited",
)
parser.add_argument(
- '-f',
- '--full',
- action='store_true',
- help='should related entities e.g. birth-places be fully serialized',
+ "-f",
+ "--full",
+ action="store_true",
+ help="should related entities e.g. birth-places be fully serialized",
)
parser.add_argument(
- '--collection',
- help='which collection?',
+ "--collection",
+ help="which collection?",
)
-
+
def handle(self, *args, **kwargs):
tei_doc = tei_header(title="ListOrg", ent_type="")
- entity_list = tei_doc.xpath("//*[local-name() = 'listOrg']")[0]
+ entity_list = tei_doc.xpath("//*[local-name() = 'listOrg']")[0]
- if kwargs['full']:
+ if kwargs["full"]:
print("full is set")
full = True
else:
print("simple")
full = False
-
- if kwargs['collection']:
+
+ if kwargs["collection"]:
try:
- col_id = int(kwargs['collection'])
+ col_id = int(kwargs["collection"])
except ValueError:
- print(f"collection needs to be an integer and not: {kwargs['collection']}")
+ print(
+ f"collection needs to be an integer and not: {kwargs['collection']}"
+ )
return False
-
+
items = Institution.objects.filter(collection=col_id)
else:
items = Institution.objects.all()
- if kwargs['limit']:
+ if kwargs["limit"]:
items = items[:25]
print(f"serialize {items.count()} Orgs")
for res in tqdm(items, total=len(items)):
- item_node = get_node_from_template(
- 'apis_tei/org.xml', res, full=full
- )
+ item_node = get_node_from_template("apis_tei/org.xml", res, full=full)
entity_list.append(item_node)
-
- with open('listorg.xml', 'w') as f:
- print(ET.tostring(tei_doc).decode('utf-8'), file=f)
+
+ with open("listorg.xml", "w") as f:
+ print(ET.tostring(tei_doc).decode("utf-8"), file=f)
print("done")
diff --git a/apis_core/apis_tei/management/commands/persons_to_tei.py b/apis_core/apis_tei/management/commands/persons_to_tei.py
index 092fbf2..1a9a893 100644
--- a/apis_core/apis_tei/management/commands/persons_to_tei.py
+++ b/apis_core/apis_tei/management/commands/persons_to_tei.py
@@ -5,58 +5,59 @@
from apis_core.apis_entities.models import Person
from apis_core.apis_tei.tei_utils import get_node_from_template, tei_header
+
class Command(BaseCommand):
- help = 'Command to serialize APIS Persons to XML/TEI persons.xml'
+ help = "Command to serialize APIS Persons to XML/TEI persons.xml"
def add_arguments(self, parser):
parser.add_argument(
- '-l',
- '--limit',
- action='store_true',
- help='number of entities should be limited',
+ "-l",
+ "--limit",
+ action="store_true",
+ help="number of entities should be limited",
)
parser.add_argument(
- '-f',
- '--full',
- action='store_true',
- help='should related entities e.g. birth-places be fully serialized',
+ "-f",
+ "--full",
+ action="store_true",
+ help="should related entities e.g. birth-places be fully serialized",
)
parser.add_argument(
- '--collection',
- help='which collection?',
+ "--collection",
+ help="which collection?",
)
-
+
def handle(self, *args, **kwargs):
tei_doc = tei_header()
- listperson = tei_doc.xpath("//*[local-name() = 'listPerson']")[0]
+ listperson = tei_doc.xpath("//*[local-name() = 'listPerson']")[0]
- if kwargs['full']:
+ if kwargs["full"]:
print("full is set")
full = True
else:
print("simple")
full = False
-
- if kwargs['collection']:
+
+ if kwargs["collection"]:
try:
- col_id = int(kwargs['collection'])
+ col_id = int(kwargs["collection"])
except ValueError:
- print(f"collection needs to be an integer and not: {kwargs['collection']}")
+ print(
+ f"collection needs to be an integer and not: {kwargs['collection']}"
+ )
return False
-
+
items = Person.objects.filter(collection=col_id)
else:
items = Person.objects.all()
- if kwargs['limit']:
+ if kwargs["limit"]:
items = items[:25]
print(f"serialize {items.count()} Persons")
for res in tqdm(items, total=len(items)):
- item_node = get_node_from_template(
- 'apis_tei/person.xml', res, full=full
- )
+ item_node = get_node_from_template("apis_tei/person.xml", res, full=full)
listperson.append(item_node)
-
- with open('listperson.xml', 'w') as f:
- print(ET.tostring(tei_doc).decode('utf-8'), file=f)
+
+ with open("listperson.xml", "w") as f:
+ print(ET.tostring(tei_doc).decode("utf-8"), file=f)
print("done")
diff --git a/apis_core/apis_tei/management/commands/places_to_tei.py b/apis_core/apis_tei/management/commands/places_to_tei.py
index 34a3f9a..74a601e 100644
--- a/apis_core/apis_tei/management/commands/places_to_tei.py
+++ b/apis_core/apis_tei/management/commands/places_to_tei.py
@@ -5,58 +5,59 @@
from apis_core.apis_entities.models import Place
from apis_core.apis_tei.tei_utils import get_node_from_template, tei_header
+
class Command(BaseCommand):
- help = 'Command to serialize APIS Places to XML/TEI places.xml'
+ help = "Command to serialize APIS Places to XML/TEI places.xml"
def add_arguments(self, parser):
parser.add_argument(
- '-l',
- '--limit',
- action='store_true',
- help='number of entities should be limited',
+ "-l",
+ "--limit",
+ action="store_true",
+ help="number of entities should be limited",
)
parser.add_argument(
- '-f',
- '--full',
- action='store_true',
- help='should related entities e.g. birth-places be fully serialized',
+ "-f",
+ "--full",
+ action="store_true",
+ help="should related entities e.g. birth-places be fully serialized",
)
parser.add_argument(
- '--collection',
- help='which collection?',
+ "--collection",
+ help="which collection?",
)
-
+
def handle(self, *args, **kwargs):
tei_doc = tei_header(title="ListPlace", ent_type="")
- listplace = tei_doc.xpath("//*[local-name() = 'listPlace']")[0]
+ listplace = tei_doc.xpath("//*[local-name() = 'listPlace']")[0]
- if kwargs['full']:
+ if kwargs["full"]:
print("full is set")
full = True
else:
print("simple")
full = False
-
- if kwargs['collection']:
+
+ if kwargs["collection"]:
try:
- col_id = int(kwargs['collection'])
+ col_id = int(kwargs["collection"])
except ValueError:
- print(f"collection needs to be an integer and not: {kwargs['collection']}")
+ print(
+ f"collection needs to be an integer and not: {kwargs['collection']}"
+ )
return False
-
+
items = Place.objects.filter(collection=col_id)
else:
items = Place.objects.all()
- if kwargs['limit']:
+ if kwargs["limit"]:
items = items[:25]
print(f"serialize {items.count()} Places")
for res in tqdm(items, total=len(items)):
- item_node = get_node_from_template(
- 'apis_tei/place.xml', res, full=full
- )
+ item_node = get_node_from_template("apis_tei/place.xml", res, full=full)
listplace.append(item_node)
-
- with open('listplace.xml', 'w') as f:
- print(ET.tostring(tei_doc).decode('utf-8'), file=f)
+
+ with open("listplace.xml", "w") as f:
+ print(ET.tostring(tei_doc).decode("utf-8"), file=f)
print("done")
diff --git a/apis_core/apis_tei/management/commands/works_to_tei.py b/apis_core/apis_tei/management/commands/works_to_tei.py
index 7890fe2..55ebf31 100644
--- a/apis_core/apis_tei/management/commands/works_to_tei.py
+++ b/apis_core/apis_tei/management/commands/works_to_tei.py
@@ -5,58 +5,59 @@
from apis_core.apis_entities.models import Work
from apis_core.apis_tei.tei_utils import get_node_from_template, tei_header
+
class Command(BaseCommand):
- help = 'Command to serialize APIS Works to XML/TEI places.xml'
+ help = "Command to serialize APIS Works to XML/TEI places.xml"
def add_arguments(self, parser):
parser.add_argument(
- '-l',
- '--limit',
- action='store_true',
- help='number of entities should be limited',
+ "-l",
+ "--limit",
+ action="store_true",
+ help="number of entities should be limited",
)
parser.add_argument(
- '-f',
- '--full',
- action='store_true',
- help='should related entities e.g. birth-places be fully serialized',
+ "-f",
+ "--full",
+ action="store_true",
+ help="should related entities e.g. birth-places be fully serialized",
)
parser.add_argument(
- '--collection',
- help='which collection?',
+ "--collection",
+ help="which collection?",
)
-
+
def handle(self, *args, **kwargs):
tei_doc = tei_header(title="ListBibl", ent_type="")
- entity_list = tei_doc.xpath("//*[local-name() = 'listBibl']")[0]
+ entity_list = tei_doc.xpath("//*[local-name() = 'listBibl']")[0]
- if kwargs['full']:
+ if kwargs["full"]:
print("full is set")
full = True
else:
print("simple")
full = False
-
- if kwargs['collection']:
+
+ if kwargs["collection"]:
try:
- col_id = int(kwargs['collection'])
+ col_id = int(kwargs["collection"])
except ValueError:
- print(f"collection needs to be an integer and not: {kwargs['collection']}")
+ print(
+ f"collection needs to be an integer and not: {kwargs['collection']}"
+ )
return False
-
+
items = Work.objects.filter(collection=col_id)
else:
items = Work.objects.all()
- if kwargs['limit']:
+ if kwargs["limit"]:
items = items[:25]
print(f"serialize {items.count()} Works")
for res in tqdm(items, total=len(items)):
- item_node = get_node_from_template(
- 'apis_tei/work.xml', res, full=full
- )
+ item_node = get_node_from_template("apis_tei/work.xml", res, full=full)
entity_list.append(item_node)
-
- with open('listwork.xml', 'w') as f:
- print(ET.tostring(tei_doc).decode('utf-8'), file=f)
+
+ with open("listwork.xml", "w") as f:
+ print(ET.tostring(tei_doc).decode("utf-8"), file=f)
print("done")
diff --git a/apis_core/apis_tei/partials.py b/apis_core/apis_tei/partials.py
index cf41ff8..1414d34 100644
--- a/apis_core/apis_tei/partials.py
+++ b/apis_core/apis_tei/partials.py
@@ -1,14 +1,14 @@
TEI_NSMAP = {
- 'tei': "http://www.tei-c.org/ns/1.0",
- 'xml': "http://www.w3.org/XML/1998/namespace",
+ "tei": "http://www.tei-c.org/ns/1.0",
+ "xml": "http://www.w3.org/XML/1998/namespace",
}
PERS_TO_TEI_DICT = {
- 'name': "{http://www.tei-c.org/ns/1.0}surname",
- 'first_name': "{http://www.tei-c.org/ns/1.0}forename",
- 'start_date': "{http://www.tei-c.org/ns/1.0}birth",
- 'end_date': "{http://www.tei-c.org/ns/1.0}death",
+ "name": "{http://www.tei-c.org/ns/1.0}surname",
+ "first_name": "{http://www.tei-c.org/ns/1.0}forename",
+ "start_date": "{http://www.tei-c.org/ns/1.0}birth",
+ "end_date": "{http://www.tei-c.org/ns/1.0}death",
}
diff --git a/apis_core/apis_tei/tei.py b/apis_core/apis_tei/tei.py
index 5e30628..9ac1c3a 100644
--- a/apis_core/apis_tei/tei.py
+++ b/apis_core/apis_tei/tei.py
@@ -44,12 +44,10 @@ def custom_escape(somestring):
class TeiEntCreator:
- def __init__(
- self, ent_dict, base_url="entity/", include_entity_tagged_texts=False
- ):
+ def __init__(self, ent_dict, base_url="entity/", include_entity_tagged_texts=False):
"""
Entry point: called from apis_core/apis_entities/api_renderers.py
-
+
ent_dict is dict representing the entity
This class is initialised, then has the serialize_full_doc method called
@@ -168,7 +166,7 @@ def create_org_node(self):
try:
node.attrib[
"{http://www.w3.org/XML/1998/namespace}lang"
- ] = "{}".format(x["isoCode_639_3"])
+ ] = "{}".format(x["isocode_639_3"])
except KeyError:
pass
node.text = x["label"]
@@ -210,7 +208,7 @@ def create_place_node(self):
try:
node.attrib[
"{http://www.w3.org/XML/1998/namespace}lang"
- ] = "{}".format(x["isoCode_639_3"])
+ ] = "{}".format(x["isocode_639_3"])
except KeyError:
pass
node.text = x["label"]
@@ -256,7 +254,7 @@ def create_person_node(self):
try:
node.attrib[
"{http://www.w3.org/XML/1998/namespace}lang"
- ] = "{}".format(x["isoCode_639_3"])
+ ] = "{}".format(x["isocode_639_3"])
except KeyError:
pass
node.text = x["label"]
@@ -507,4 +505,3 @@ def stand_off_to_inline(text, annot):
i = j
return "".join(parts)
-
diff --git a/apis_core/apis_tei/tei_ac.py b/apis_core/apis_tei/tei_ac.py
index 724823c..f78dfd1 100644
--- a/apis_core/apis_tei/tei_ac.py
+++ b/apis_core/apis_tei/tei_ac.py
@@ -7,61 +7,61 @@
class TeiEntAc(autocomplete.Select2ListView):
-
def get(self, request, *args, **kwargs):
page_size = 200
- offset = (int(self.request.GET.get('page', 1))-1)*page_size
- ac_type = self.kwargs['entity']
+ offset = (int(self.request.GET.get("page", 1)) - 1) * page_size
+ ac_type = self.kwargs["entity"]
if ac_type == "org":
ac_type = "institution"
choices = []
- headers = {'Content-Type': 'application/json'}
+ headers = {"Content-Type": "application/json"}
ent_model = AbstractEntity.get_entity_class_of_name(ac_type)
q = self.q.strip()
res = ent_model.objects.filter(name__startswith=q)
- for r in res[offset:offset+page_size]:
+ for r in res[offset : offset + page_size]:
dates = "time: {} - {}".format(r.start_date, r.end_date)
f = dict()
- f['id'] = f"{request.build_absolute_uri('/entity/')}{r.pk}"
- if ac_type == 'institution':
- f['type'] = "org"
+ f["id"] = f"{request.build_absolute_uri('/entity/')}{r.pk}"
+ if ac_type == "institution":
+ f["type"] = "org"
else:
- f['type'] = "{}".format(ac_type)
- f['name'] = "{}".format(str(r))
- f['description'] = "{}".format(dates)
+ f["type"] = "{}".format(ac_type)
+ f["name"] = "{}".format(str(r))
+ f["description"] = "{}".format(dates)
choices.append(f)
- return http.HttpResponse(json.dumps({
- 'item': choices + [],
- 'pagination': {'more': True}
- }), content_type='application/json')
+ return http.HttpResponse(
+ json.dumps({"item": choices + [], "pagination": {"more": True}}),
+ content_type="application/json",
+ )
class TeiCompleterAc(autocomplete.Select2ListView):
-
def get(self, request, *args, **kwargs):
page_size = 200
- offset = (int(self.request.GET.get('page', 1))-1)*page_size
- ac_type = self.kwargs['entity']
+ offset = (int(self.request.GET.get("page", 1)) - 1) * page_size
+ ac_type = self.kwargs["entity"]
if ac_type == "org":
ac_type = "institution"
choices = []
- headers = {'Content-Type': 'application/json'}
+ headers = {"Content-Type": "application/json"}
ent_model = AbstractEntity.get_entity_class_of_name(ac_type)
q = self.q.strip()
res = ent_model.objects.filter(name__startswith=q)
- for r in res[offset:offset+page_size]:
+ for r in res[offset : offset + page_size]:
dates = "time: {} - {}".format(r.start_date, r.end_date)
f = dict()
- f['tc:value'] = "{}".format(r.uri_set.all()[0])
- if ac_type == 'institution':
+ f["tc:value"] = "{}".format(r.uri_set.all()[0])
+ if ac_type == "institution":
ent_type = "org"
else:
ent_type = "{}".format(ac_type)
- f['tc:description'] = f"name: {str(r)}, type: {ent_type}, dates: {dates}".format(dates)
+ f[
+ "tc:description"
+ ] = f"name: {str(r)}, type: {ent_type}, dates: {dates}".format(dates)
choices.append(f)
- return http.HttpResponse(json.dumps({
- 'tc:suggestion': choices + [],
- 'pagination': {'more': True}
- }), content_type='application/json')
+ return http.HttpResponse(
+ json.dumps({"tc:suggestion": choices + [], "pagination": {"more": True}}),
+ content_type="application/json",
+ )
diff --git a/apis_core/apis_tei/tei_utils.py b/apis_core/apis_tei/tei_utils.py
index 19094fe..7833618 100644
--- a/apis_core/apis_tei/tei_utils.py
+++ b/apis_core/apis_tei/tei_utils.py
@@ -4,7 +4,7 @@
from apis_core.apis_entities.models import Work, Place, Person, Institution
from apis_core.apis_relations.models import PlacePlace, PersonWork
from apis_core.apis_vocabularies.models import PersonWorkRelation
-from apis_core.helper_functions.utils import get_child_classes
+from apis_core.helper_functions.utils import get_child_classes
try:
birth_rel = settings.BIRTH_REL
@@ -36,49 +36,63 @@
else:
author_rels = False
+
def get_part_of_relation(res):
items = []
- for x in PlacePlace.objects.filter(related_placeB=res).filter(relation_type__id__in=pl_b_located_in):
- items.append(x.related_placeA)
- for x in PlacePlace.objects.filter(related_placeA=res).filter(relation_type__id__in=pl_a_part_of):
- items.append(x.related_placeB)
+ for x in PlacePlace.objects.filter(related_placeb=res).filter(
+ relation_type__id__in=pl_b_located_in
+ ):
+ items.append(x.related_placea)
+ for x in PlacePlace.objects.filter(related_placea=res).filter(
+ relation_type__id__in=pl_a_part_of
+ ):
+ items.append(x.related_placeb)
return list(set(items))
+
def get_context(res):
-
+
context = {}
- context['object'] = res
- context['org_located_in'] = []
- context['birth_rel'] = []
- context['death_rel'] = []
- context['pl_located_in'] = []
- context['author_rels'] = []
+ context["object"] = res
+ context["org_located_in"] = []
+ context["birth_rel"] = []
+ context["death_rel"] = []
+ context["pl_located_in"] = []
+ context["author_rels"] = []
if isinstance(res, Work):
person_work_ids = author_rels
try:
- context['author_rels'] = PersonWork.objects.filter(relation_type__in=person_work_ids, related_work=res)
+ context["author_rels"] = PersonWork.objects.filter(
+ relation_type__in=person_work_ids, related_work=res
+ )
except ValueError:
- context['author_rels'] = []
+ context["author_rels"] = []
if org_located_in and isinstance(res, Institution):
try:
- context['org_located_in'] = res.institutionplace_set.filter(relation_type__in=org_located_in)
+ context["org_located_in"] = res.institutionplace_set.filter(
+ relation_type__in=org_located_in
+ )
except AttributeError:
pass
if isinstance(res, Person):
if birth_rel:
try:
- context['birth_rel'] = res.personplace_set.filter(relation_type__in=birth_rel)
+ context["birth_rel"] = res.personplace_set.filter(
+ relation_type__in=birth_rel
+ )
except AttributeError:
pass
if death_rel:
try:
- context['death_rel'] = res.personplace_set.filter(relation_type__in=death_rel)
+ context["death_rel"] = res.personplace_set.filter(
+ relation_type__in=death_rel
+ )
except AttributeError:
pass
if isinstance(res, Place):
if pl_a_part_of and pl_b_located_in:
try:
- context['pl_located_in'] = get_part_of_relation(res)
+ context["pl_located_in"] = get_part_of_relation(res)
except ValueError:
pass
return context
@@ -87,22 +101,17 @@ def get_context(res):
def get_node_from_template(template_path, res, full=True):
template = get_template(template_path)
context = get_context(res)
- context['FULL'] = full
+ context["FULL"] = full
temp_str = f"{template.render(context=context)}"
node = ET.fromstring(temp_str)
return node
def tei_header(
- title="ListPerson",
- ent_type="",
- template_path='apis_tei/tei.xml'
+ title="ListPerson", ent_type="", template_path="apis_tei/tei.xml"
):
template = get_template(template_path)
- context = {
- "title": title,
- "ent_type": ent_type
- }
+ context = {"title": title, "ent_type": ent_type}
temp_str = f"{template.render(context=context)}"
node = ET.fromstring(temp_str)
return node
diff --git a/apis_core/apis_tei/views.py b/apis_core/apis_tei/views.py
index fdfad63..eea869e 100644
--- a/apis_core/apis_tei/views.py
+++ b/apis_core/apis_tei/views.py
@@ -11,57 +11,72 @@
def person_as_tei(request, pk):
- full = request.GET.get('full')
+ full = request.GET.get("full")
model = Person
res = get_object_from_pk_or_uri(request, pk)
if not isinstance(res, model):
- return HttpResponse(f"Requested object is not an instance of {model.__name__}", content_type="text/plain")
- doc = get_node_from_template('apis_tei/person.xml', res, full=full)
- tei = ET.tostring(doc, pretty_print=True, encoding='UTF-8')
+ return HttpResponse(
+ f"Requested object is not an instance of {model.__name__}",
+ content_type="text/plain",
+ )
+ doc = get_node_from_template("apis_tei/person.xml", res, full=full)
+ tei = ET.tostring(doc, pretty_print=True, encoding="UTF-8")
return HttpResponse(tei, content_type="application/xml")
def place_as_tei(request, pk):
- full = request.GET.get('full')
+ full = request.GET.get("full")
model = Place
res = get_object_from_pk_or_uri(request, pk)
if not isinstance(res, model):
- return HttpResponse(f"Requested object is not an instance of {model.__name__}", content_type="text/plain")
- doc = get_node_from_template('apis_tei/place.xml', res, full=full)
- tei = ET.tostring(doc, pretty_print=True, encoding='UTF-8')
+ return HttpResponse(
+ f"Requested object is not an instance of {model.__name__}",
+ content_type="text/plain",
+ )
+ doc = get_node_from_template("apis_tei/place.xml", res, full=full)
+ tei = ET.tostring(doc, pretty_print=True, encoding="UTF-8")
return HttpResponse(tei, content_type="application/xml")
def work_as_tei(request, pk):
- full = request.GET.get('full')
+ full = request.GET.get("full")
model = Work
res = get_object_from_pk_or_uri(request, pk)
if not isinstance(res, model):
- return HttpResponse(f"Requested object is not an instance of {model.__name__}", content_type="text/plain")
- doc = get_node_from_template('apis_tei/work.xml', res, full=full)
- tei = ET.tostring(doc, pretty_print=True, encoding='UTF-8')
+ return HttpResponse(
+ f"Requested object is not an instance of {model.__name__}",
+ content_type="text/plain",
+ )
+ doc = get_node_from_template("apis_tei/work.xml", res, full=full)
+ tei = ET.tostring(doc, pretty_print=True, encoding="UTF-8")
return HttpResponse(tei, content_type="application/xml")
def org_as_tei(request, pk):
- full = request.GET.get('full')
+ full = request.GET.get("full")
model = Institution
res = get_object_from_pk_or_uri(request, pk)
if not isinstance(res, model):
- return HttpResponse(f"Requested object is not an instance of {model.__name__}", content_type="text/plain")
- doc = get_node_from_template('apis_tei/org.xml', res, full=full)
- tei = ET.tostring(doc, pretty_print=True, encoding='UTF-8')
+ return HttpResponse(
+ f"Requested object is not an instance of {model.__name__}",
+ content_type="text/plain",
+ )
+ doc = get_node_from_template("apis_tei/org.xml", res, full=full)
+ tei = ET.tostring(doc, pretty_print=True, encoding="UTF-8")
return HttpResponse(tei, content_type="application/xml")
def uri_to_tei(request):
- requested_uri = request.GET.get('uri', None)
+ requested_uri = request.GET.get("uri", None)
if requested_uri is not None:
uri = get_object_or_404(Uri, uri=requested_uri)
uri_entity_id = uri.entity.id
uri_entity_class = uri.entity.get_child_entity()
uri_entity_class_name = uri_entity_class.__class__.__name__.lower()
- redirect_url = f'/apis/entities/tei/{uri_entity_class_name}/{uri_entity_id}'
+ redirect_url = f"/apis/entities/tei/{uri_entity_class_name}/{uri_entity_id}"
return redirect(redirect_url)
else:
- return HttpResponse(f"no URI provided, please try e.g. uri-to-tei?uri=https://whatever.you/want", content_type="text/plain")
+ return HttpResponse(
+ f"no URI provided, please try e.g. uri-to-tei?uri=https://whatever.you/want",
+ content_type="text/plain",
+ )
diff --git a/apis_core/apis_vis/api_views.py b/apis_core/apis_vis/api_views.py
index 0e890b1..f313e22 100644
--- a/apis_core/apis_vis/api_views.py
+++ b/apis_core/apis_vis/api_views.py
@@ -14,16 +14,16 @@ class GetVisJson(ListAPIView):
# TODO: add a generic filter thing
def get_serializer(self, instance=None, data=None, many=False, partial=False):
- vis = self.request.query_params.get('vis', None)
- if vis == 'av-age':
+ vis = self.request.query_params.get("vis", None)
+ if vis == "av-age":
return VisAgeSerializer(self.get_queryset(), many=False)
- elif vis == 'avg-relations':
+ elif vis == "avg-relations":
return AvRelations(self.get_queryset(), many=False)
else:
return None
def get_queryset(self, **kwargs):
- relation = self.kwargs['relation'].lower()
+ relation = self.kwargs["relation"].lower()
relation_model = AbstractRelation.get_relation_class_of_name(relation)
print("from get_queryset {}".format(relation))
queryset = relation_model.objects.all()
diff --git a/apis_core/apis_vis/apps.py b/apis_core/apis_vis/apps.py
index ab0c457..2b5c1a1 100644
--- a/apis_core/apis_vis/apps.py
+++ b/apis_core/apis_vis/apps.py
@@ -2,4 +2,4 @@
class EntitiesConfig(AppConfig):
- name = 'apis_core.apis_vis'
+ name = "apis_core.apis_vis"
diff --git a/apis_core/apis_vis/serializers.py b/apis_core/apis_vis/serializers.py
index 74cc0a4..d7e9546 100644
--- a/apis_core/apis_vis/serializers.py
+++ b/apis_core/apis_vis/serializers.py
@@ -6,96 +6,99 @@
class GenericBaseSerializer(serializers.BaseSerializer):
-
def to_representation(self, obj):
data = {
"items": "some",
- "title": "{}".format('Members by Year'),
- "subtitle": "Person Institution relation type {}".format('some type'),
+ "title": "{}".format("Members by Year"),
+ "subtitle": "Person Institution relation type {}".format("some type"),
"legendy": "legendy",
"legendx": "legendx",
"categories": "sorted(dates)",
"measuredObject": "{} relations".format("find some variable"),
"ymin": 0,
"x_axis": "something",
- "payload": "something"
+ "payload": "something",
}
return data
class AvRelations(GenericBaseSerializer):
-
def to_representation(self, obj):
print(obj[0].__class__.__name__)
qs = obj.filter(start_date__isnull=False).filter(end_date__isnull=False)
- start_year = int(str(qs.order_by('start_date')[0].start_date)[:4])
- end_year = int(str(qs.order_by('-start_date')[0].start_date)[:4])
+ start_year = int(str(qs.order_by("start_date")[0].start_date)[:4])
+ end_year = int(str(qs.order_by("-start_date")[0].start_date)[:4])
qs = [
{
- 'year': x,
- 'members_new': qs.filter(start_date__year=x).count(),
- 'members_all': qs.filter(
+ "year": x,
+ "members_new": qs.filter(start_date__year=x).count(),
+ "members_all": qs.filter(
start_date__year__lte=x, end_date__year__gte=x
).count(),
- } for x in range(start_year, end_year)
+ }
+ for x in range(start_year, end_year)
]
df = pd.DataFrame(qs)
payload = [
{
- 'name': 'all members',
- 'data': [x for x in df[['members_all']].values.tolist()]
+ "name": "all members",
+ "data": [x for x in df[["members_all"]].values.tolist()],
},
{
- 'name': 'new members',
- 'data': [x for x in df[['members_new']].values.tolist()]
- }
+ "name": "new members",
+ "data": [x for x in df[["members_new"]].values.tolist()],
+ },
]
data = {
"items": "some",
- "title": "{}".format('Members by Year'),
- "subtitle": "Person Institution relation type {}".format('some type'),
+ "title": "{}".format("Members by Year"),
+ "subtitle": "Person Institution relation type {}".format("some type"),
"legendy": "legendy",
"legendx": "legendx",
"categories": "sorted(dates)",
"measuredObject": "{} relations".format("find some variable"),
"ymin": 0,
- "x_axis": df['year'].values.tolist(),
- "payload": payload
+ "x_axis": df["year"].values.tolist(),
+ "payload": payload,
}
return data
class VisAgeSerializer(serializers.BaseSerializer):
-
def to_representation(self, obj):
qs = [
{
- 'year': x,
- 'members_new': obj.filter(start_date__year=x).count(),
- 'avg_birth_new': obj.filter(start_date__year=x)
- .aggregate(
- Avg('related_person__start_date__year')
- )['related_person__start_date__year__avg'],
- 'members_all': obj.filter(
+ "year": x,
+ "members_new": obj.filter(start_date__year=x).count(),
+ "avg_birth_new": obj.filter(start_date__year=x).aggregate(
+ Avg("related_person__start_date__year")
+ )["related_person__start_date__year__avg"],
+ "members_all": obj.filter(
start_date__year__lte=x, end_date__year__gte=x
).count(),
- 'avg_birth': obj.filter(start_date__year__lte=x, end_date__year__gte=x)
- .aggregate(
- Avg('related_person__start_date__year')
- )['related_person__start_date__year__avg']
- } for x in range(1847, 2015)
+ "avg_birth": obj.filter(
+ start_date__year__lte=x, end_date__year__gte=x
+ ).aggregate(Avg("related_person__start_date__year"))[
+ "related_person__start_date__year__avg"
+ ],
+ }
+ for x in range(1847, 2015)
]
df = pd.DataFrame(qs)
- df['avg_age_new'] = df.apply(lambda row: calculate_age(row, 'avg_birth_new'), axis=1)
- df['avg_age_all'] = df.apply(lambda row: calculate_age(row, 'avg_birth'), axis=1)
+ df["avg_age_new"] = df.apply(
+ lambda row: calculate_age(row, "avg_birth_new"), axis=1
+ )
+ df["avg_age_all"] = df.apply(
+ lambda row: calculate_age(row, "avg_birth"), axis=1
+ )
payload = [
{
- 'name': 'average age all',
- 'data': [x for x in df[['avg_age_all']].values.tolist()]
+ "name": "average age all",
+ "data": [x for x in df[["avg_age_all"]].values.tolist()],
},
{
- 'name': 'average age new',
- 'data': [x for x in df[['avg_age_new']].values.tolist()]
- }
+ "name": "average age new",
+ "data": [x for x in df[["avg_age_new"]].values.tolist()],
+ },
]
return payload
diff --git a/apis_core/apis_vis/urls.py b/apis_core/apis_vis/urls.py
index 53b146c..c0c411b 100644
--- a/apis_core/apis_vis/urls.py
+++ b/apis_core/apis_vis/urls.py
@@ -2,20 +2,26 @@
from . import views, api_views
-app_name = 'apis_vis'
+app_name = "apis_vis"
urlpatterns = [
- url(r'^heatmap/', views.HeatMapView.as_view(), name='heatmap_view'),
- url(r'^heatmap-data/', views.get_heatmap_data, name='get_heatmap_data'),
- url(r'^avg-age-data/', views.get_average_age_data, name='get_avg_age_data'),
- url(r'^avg-age/', views.AvgAge.as_view(), name='avgage_view'),
- url(r'^avg-members-data/', views.get_average_members_data, name='get_avg_members_data'),
- url(r'^avg-members/', views.MembersAmountPerYear.as_view(), name='avg_members_view'),
+ url(r"^heatmap/", views.HeatMapView.as_view(), name="heatmap_view"),
+ url(r"^heatmap-data/", views.get_heatmap_data, name="get_heatmap_data"),
+ url(r"^avg-age-data/", views.get_average_age_data, name="get_avg_age_data"),
+ url(r"^avg-age/", views.AvgAge.as_view(), name="avgage_view"),
url(
- r'^(?P[a-z]+)/data/',
+ r"^avg-members-data/",
+ views.get_average_members_data,
+ name="get_avg_members_data",
+ ),
+ url(
+ r"^avg-members/", views.MembersAmountPerYear.as_view(), name="avg_members_view"
+ ),
+ url(
+ r"^(?P[a-z]+)/data/",
api_views.GetVisJson.as_view(),
- name='person-institution-data'
+ name="person-institution-data",
),
- url(r'^inst-range-data/', views.get_inst_range_data, name='get_inst_range_data'),
- url(r'^inst-range/', views.InstRange.as_view(), name='inst_range_view'),
+ url(r"^inst-range-data/", views.get_inst_range_data, name="get_inst_range_data"),
+ url(r"^inst-range/", views.InstRange.as_view(), name="inst_range_view"),
]
diff --git a/apis_core/apis_vis/utils.py b/apis_core/apis_vis/utils.py
index 28d6686..72255c9 100644
--- a/apis_core/apis_vis/utils.py
+++ b/apis_core/apis_vis/utils.py
@@ -1,6 +1,6 @@
def calculate_age(row, age_field):
try:
- year = row['year']
+ year = row["year"]
except ValueError:
year = None
try:
@@ -8,6 +8,6 @@ def calculate_age(row, age_field):
except ValueError:
age = None
if year and age:
- return year-age
+ return year - age
else:
return 0
diff --git a/apis_core/apis_vis/views.py b/apis_core/apis_vis/views.py
index 44db0dc..c2f5602 100644
--- a/apis_core/apis_vis/views.py
+++ b/apis_core/apis_vis/views.py
@@ -8,149 +8,161 @@
def get_inst_range_data(request):
- df = pd.DataFrame(list(InstitutionInstitution.objects.filter(
- relation_type__name="ist Teil von").distinct().values_list(
- 'related_institutionA__name',
- 'related_institutionA__start_date__year',
- 'related_institutionA__end_date__year',
- 'related_institutionB__name'
- )
- ), columns=['name', 'start_year', 'end_year', 'teil von']).fillna(2018)
- df.sort_values('start_year')
+ df = pd.DataFrame(
+ list(
+ InstitutionInstitution.objects.filter(relation_type__name="ist Teil von")
+ .distinct()
+ .values_list(
+ "related_institutionA__name",
+ "related_institutionA__start_date__year",
+ "related_institutionA__end_date__year",
+ "related_institutionB__name",
+ )
+ ),
+ columns=["name", "start_year", "end_year", "teil von"],
+ ).fillna(2018)
+ df.sort_values("start_year")
data = {
"items": "some",
- "title": "{}".format('Kommissionen'),
- "subtitle": "Person Institution relation type {}".format('some type'),
+ "title": "{}".format("Kommissionen"),
+ "subtitle": "Person Institution relation type {}".format("some type"),
"legendy": "legendy",
"legendx": "legendx",
"categories": "sorted(dates)",
"measuredObject": "{}".format("Persons average Age"),
"ymin": 0,
- "x_axis": df['name'].values.tolist(),
+ "x_axis": df["name"].values.tolist(),
"payload": [
{
- 'name': 'Kommissionen',
- 'data': df[['start_year', 'end_year']].values.tolist()
+ "name": "Kommissionen",
+ "data": df[["start_year", "end_year"]].values.tolist(),
}
- ]
+ ],
}
return JsonResponse(data, safe=False)
def get_average_members_data(request):
- rel_type = request.GET.get('rel-type')
- rel_inst = request.GET.get('rel-inst')
- start_year = request.GET.get('start-year')
- end_year = request.GET.get('start-year')
+ rel_type = request.GET.get("rel-type")
+ rel_inst = request.GET.get("rel-inst")
+ start_year = request.GET.get("start-year")
+ end_year = request.GET.get("start-year")
per_inst = PersonInstitution.objects.filter(related_institution_id__in=[3, 2])
if rel_type:
data = []
else:
- start_year = int(str(per_inst.order_by('start_date')[0].start_date)[:4])
- end_year = int(str(per_inst.order_by('-start_date')[0].start_date)[:4])
+ start_year = int(str(per_inst.order_by("start_date")[0].start_date)[:4])
+ end_year = int(str(per_inst.order_by("-start_date")[0].start_date)[:4])
qs = [
{
- 'year': x,
- 'members_new': per_inst.filter(start_date__year=x).count(),
- 'members_all': per_inst.filter(
+ "year": x,
+ "members_new": per_inst.filter(start_date__year=x).count(),
+ "members_all": per_inst.filter(
start_date__year__lte=x, end_date__year__gte=x
).count(),
- } for x in range(1847, 2015)
+ }
+ for x in range(1847, 2015)
]
df = pd.DataFrame(qs)
payload = [
{
- 'name': 'all members',
- 'data': [x for x in df[['members_all']].values.tolist()]
+ "name": "all members",
+ "data": [x for x in df[["members_all"]].values.tolist()],
},
{
- 'name': 'new members',
- 'data': [x for x in df[['members_new']].values.tolist()]
- }
+ "name": "new members",
+ "data": [x for x in df[["members_new"]].values.tolist()],
+ },
]
data = {
"items": "some",
- "title": "{}".format('Members by Year'),
- "subtitle": "Person Institution relation type {}".format('some type'),
+ "title": "{}".format("Members by Year"),
+ "subtitle": "Person Institution relation type {}".format("some type"),
"legendy": "legendy",
"legendx": "legendx",
"categories": "sorted(dates)",
"measuredObject": "{}".format("Persons average Age"),
"ymin": 0,
- "x_axis": df['year'].values.tolist(),
- "payload": payload
+ "x_axis": df["year"].values.tolist(),
+ "payload": payload,
}
return JsonResponse(data, safe=False)
def get_average_age_data(request):
- rel_type = request.GET.get('rel-type')
- rel_inst = request.GET.get('rel-inst')
- start_year = request.GET.get('start-year')
- end_year = request.GET.get('start-year')
+ rel_type = request.GET.get("rel-type")
+ rel_inst = request.GET.get("rel-inst")
+ start_year = request.GET.get("start-year")
+ end_year = request.GET.get("start-year")
per_inst = PersonInstitution.objects.filter(related_institution_id__in=[3, 2])
if rel_type:
data = []
else:
- start_year = int(str(per_inst.order_by('start_date')[0].start_date)[:4])
- end_year = int(str(per_inst.order_by('-start_date')[0].start_date)[:4])
+ start_year = int(str(per_inst.order_by("start_date")[0].start_date)[:4])
+ end_year = int(str(per_inst.order_by("-start_date")[0].start_date)[:4])
qs = [
{
- 'year': x,
- 'members_new': per_inst.filter(start_date__year=x).count(),
- 'avg_birth_new': per_inst.filter(start_date__year=x)
- .aggregate(
- Avg('related_person__start_date__year')
- )['related_person__start_date__year__avg'],
- 'members_all': per_inst.filter(
+ "year": x,
+ "members_new": per_inst.filter(start_date__year=x).count(),
+ "avg_birth_new": per_inst.filter(start_date__year=x).aggregate(
+ Avg("related_person__start_date__year")
+ )["related_person__start_date__year__avg"],
+ "members_all": per_inst.filter(
start_date__year__lte=x, end_date__year__gte=x
).count(),
- 'avg_birth': per_inst.filter(start_date__year__lte=x, end_date__year__gte=x)
- .aggregate(
- Avg('related_person__start_date__year')
- )['related_person__start_date__year__avg']
- } for x in range(1847, 2015)
+ "avg_birth": per_inst.filter(
+ start_date__year__lte=x, end_date__year__gte=x
+ ).aggregate(Avg("related_person__start_date__year"))[
+ "related_person__start_date__year__avg"
+ ],
+ }
+ for x in range(1847, 2015)
]
df = pd.DataFrame(qs)
- df['avg_age_new'] = df.apply(lambda row: calculate_age(row, 'avg_birth_new'), axis=1)
- df['avg_age_all'] = df.apply(lambda row: calculate_age(row, 'avg_birth'), axis=1)
+ df["avg_age_new"] = df.apply(
+ lambda row: calculate_age(row, "avg_birth_new"), axis=1
+ )
+ df["avg_age_all"] = df.apply(
+ lambda row: calculate_age(row, "avg_birth"), axis=1
+ )
payload = [
{
- 'name': 'average age all',
- 'data': [x for x in df[['avg_age_all']].values.tolist()]
+ "name": "average age all",
+ "data": [x for x in df[["avg_age_all"]].values.tolist()],
},
{
- 'name': 'average age new',
- 'data': [x for x in df[['avg_age_new']].values.tolist()]
- }
+ "name": "average age new",
+ "data": [x for x in df[["avg_age_new"]].values.tolist()],
+ },
]
data = {
"items": "some",
- "title": "{}".format('Average Age by Year'),
- "subtitle": "Person Institution relation type {}".format('some type'),
+ "title": "{}".format("Average Age by Year"),
+ "subtitle": "Person Institution relation type {}".format("some type"),
"legendy": "legendy",
"legendx": "legendx",
"categories": "sorted(dates)",
"measuredObject": "{}".format("Persons average Age"),
"ymin": 0,
- "x_axis": df['year'].values.tolist(),
- "payload": payload
+ "x_axis": df["year"].values.tolist(),
+ "payload": payload,
}
return JsonResponse(data, safe=False)
def get_heatmap_data(request):
- rel_type = request.GET.get('rel-type')
+ rel_type = request.GET.get("rel-type")
places = [
(
x.related_place.lat,
x.related_place.lng,
- ) for x in PersonPlace.objects.filter(
- relation_type__name=rel_type
- ).exclude(related_place__lat__isnull=True)
+ )
+ for x in PersonPlace.objects.filter(relation_type__name=rel_type).exclude(
+ related_place__lat__isnull=True
+ )
]
return JsonResponse(places, safe=False)
diff --git a/apis_core/apis_vocabularies/admin.py b/apis_core/apis_vocabularies/admin.py
index 82d3ace..9842c17 100644
--- a/apis_core/apis_vocabularies/admin.py
+++ b/apis_core/apis_vocabularies/admin.py
@@ -7,16 +7,16 @@
class BaseAdminVocabularies(admin.ModelAdmin):
- '''Base class used to store the User foreign key in the background when someone adds a vocab.'''
+ """Base class used to store the User foreign key in the background when someone adds a vocab."""
- search_fields = ('name', 'parent_class__name')
- exclude = ('userAdded',)
+ search_fields = ("name", "parent_class__name")
+ exclude = ("userAdded",)
actions = [csvexport]
def get_fields(self, request, obj=None):
lst = super(BaseAdminVocabularies, self).get_fields(request, obj=None)
if not request.user.is_superuser:
- lst.remove('status')
+ lst.remove("status")
return lst
def get_queryset(self, request):
@@ -31,25 +31,28 @@ def save_model(self, request, obj, form, change):
obj.save()
def formfield_for_foreignkey(self, db_field, request, **kwargs):
- attrs = {'data-placeholder': 'Type to get suggestions',
- 'data-minimum-input-length': getattr(settings, "APIS_MIN_CHAR", 3),
- 'data-html': True}
+ attrs = {
+ "data-placeholder": "Type to get suggestions",
+ "data-minimum-input-length": getattr(settings, "APIS_MIN_CHAR", 3),
+ "data-html": True,
+ }
c_name = db_field.model.__name__
qs = super(BaseAdminVocabularies, self).get_queryset(request)
- if c_name.endswith('Relation') and db_field.name == 'parent_class':
+ if c_name.endswith("Relation") and db_field.name == "parent_class":
qs = db_field.model
if db_field.name == "parent_class" and request.user.is_superuser:
kwargs["queryset"] = qs.all()
elif db_field.name == "parent_class":
- kwargs["queryset"] = qs.filter(userAdded__groups__in=request.user.groups.all())
- kwargs['widget'] = autocomplete.Select2(
+ kwargs["queryset"] = qs.filter(
+ userAdded__groups__in=request.user.groups.all()
+ )
+ kwargs["widget"] = autocomplete.Select2(
url=reverse(
- 'apis:apis_vocabularies:generic_vocabularies_autocomplete',
- kwargs={
- 'vocab': self.model.__name__.lower(),
- 'direct': 'normal'
- }
- ), attrs=attrs)
+ "apis:apis_vocabularies:generic_vocabularies_autocomplete",
+ kwargs={"vocab": self.model.__name__.lower(), "direct": "normal"},
+ ),
+ attrs=attrs,
+ )
return super(BaseAdminVocabularies, self).formfield_for_foreignkey(
db_field, request, **kwargs
@@ -57,17 +60,16 @@ def formfield_for_foreignkey(self, db_field, request, **kwargs):
class VocabsRelationAdmin(BaseAdminVocabularies):
- list_display = ('name', 'label')
- search_fields = ('name', 'parent_class__name')
-
+ list_display = ("name", "label")
+ search_fields = ("name", "parent_class__name")
-app = apps.get_app_config('apis_vocabularies')
+app = apps.get_app_config("apis_vocabularies")
for model_name, model in app.models.items():
- if model_name.endswith('relation'):
+ if model_name.endswith("relation"):
admin.site.register(model, VocabsRelationAdmin)
else:
admin.site.register(model, BaseAdminVocabularies)
diff --git a/apis_core/apis_vocabularies/api_renderers.py b/apis_core/apis_vocabularies/api_renderers.py
index 18a8527..36df595 100644
--- a/apis_core/apis_vocabularies/api_renderers.py
+++ b/apis_core/apis_vocabularies/api_renderers.py
@@ -10,24 +10,33 @@
from webpage.utils import PROJECT_METADATA
-base_uri_web = getattr(settings, 'APIS_BASE_URI', 'http://apis.info')
-if base_uri_web.endswith('/'):
+base_uri_web = getattr(settings, "APIS_BASE_URI", "http://apis.info")
+if base_uri_web.endswith("/"):
base_uri_web = base_uri_web[:-1]
-lang = getattr(settings, 'LANGUAGE_CODE', 'de')
+lang = getattr(settings, "LANGUAGE_CODE", "de")
class VocabToSkos(renderers.BaseRenderer):
media_type = "text/rdf"
- def render(self, data1, media_type=None, g=None, renderer_context=None, format1=None, binary=True, store=None):
+ def render(
+ self,
+ data1,
+ media_type=None,
+ g=None,
+ renderer_context=None,
+ format1=None,
+ binary=True,
+ store=None,
+ ):
if g is None:
g = Graph()
set_skos = getattr(settings, "APIS_SKOSMOS")
- base_uri = set_skos.get('url')
- if base_uri.endswith('/'):
+ base_uri = set_skos.get("url")
+ if base_uri.endswith("/"):
base_uri = base_uri[:-1]
- title = PROJECT_METADATA.get('title', 'TITLE')
+ title = PROJECT_METADATA.get("title", "TITLE")
v_title = set_skos.get("vocabs-name", False)
if not v_title:
v_title = f"{title.lower()}thesaurus/"
@@ -36,34 +45,52 @@ def render(self, data1, media_type=None, g=None, renderer_context=None, format1=
g.add((uri, RDFS.label, Literal(f"{title}Schema", lang=lang)))
g.add((RDF.Description, RDF.about, uri))
g.add((uri, RDF.type, SKOS.ConceptScheme))
- g.add((uri, DC.description, Literal(f"{set_skos.get('description', 'DESCRIPTION')}", lang=lang)))
- g.add((uri, DC.license, URIRef(set_skos.get("license", "https://opensource.org/licenses/MIT"))))
+ g.add(
+ (
+ uri,
+ DC.description,
+ Literal(f"{set_skos.get('description', 'DESCRIPTION')}", lang=lang),
+ )
+ )
+ g.add(
+ (
+ uri,
+ DC.license,
+ URIRef(set_skos.get("license", "https://opensource.org/licenses/MIT")),
+ )
+ )
g.add((uri, DC.relation, URIRef(base_uri_web)))
-
+
cols = {}
for d in data1:
if not cols.get(d["vocab_name"], False):
vc = URIRef(f"{uri_1}/{d['vocab_name']}")
g.add((vc, RDF.type, SKOS.Collection))
- g.add((vc, SKOS.prefLabel, Literal(d['vocab_name'], lang=lang)))
+ g.add((vc, SKOS.prefLabel, Literal(d["vocab_name"], lang=lang)))
cols[d["vocab_name"]] = vc
else:
vc = cols.get(d["vocab_name"])
conc = URIRef(f"{uri_1}/{d['id']}")
g.add((vc, SKOS.member, conc))
g.add((conc, RDF.type, SKOS.Concept))
- g.add((conc, SKOS.prefLabel, Literal(d['name'], lang=lang)))
- if d['name'] != d['label']:
- g.add((conc, SKOS.altLabel, Literal(d['label'], lang=lang)))
- rev = d.get('name_reverse', False)
+ g.add((conc, SKOS.prefLabel, Literal(d["name"], lang=lang)))
+ if d["name"] != d["label"]:
+ g.add((conc, SKOS.altLabel, Literal(d["label"], lang=lang)))
+ rev = d.get("name_reverse", False)
if rev:
g.add((conc, SKOS.altLabel, Literal(f"reverse name: {rev}", lang=lang)))
- if d['name_reverse'] != d['label_reverse']:
- g.add((conc, SKOS.altLabel, Literal(f"reverse label: {d['label_reverse']}", lang=lang)))
- if d.get('userAdded', False):
- if (uri, DC.creator, Literal(d['userAdded'], lang=lang)) not in g:
- g.add((uri, DC.creator, Literal(d['userAdded'], lang=lang)))
- broader = d.get('parent_class', False)
+ if d["name_reverse"] != d["label_reverse"]:
+ g.add(
+ (
+ conc,
+ SKOS.altLabel,
+ Literal(f"reverse label: {d['label_reverse']}", lang=lang),
+ )
+ )
+ if d.get("userAdded", False):
+ if (uri, DC.creator, Literal(d["userAdded"], lang=lang)) not in g:
+ g.add((uri, DC.creator, Literal(d["userAdded"], lang=lang)))
+ broader = d.get("parent_class", False)
if broader:
g.add((conc, SKOS.broader, URIRef(f"{uri_1}/{broader}")))
else:
diff --git a/apis_core/apis_vocabularies/api_views.py b/apis_core/apis_vocabularies/api_views.py
index dda5f5c..57539c8 100644
--- a/apis_core/apis_vocabularies/api_views.py
+++ b/apis_core/apis_vocabularies/api_views.py
@@ -2,21 +2,58 @@
from rest_framework import viewsets
from .models import (
- InstitutionInstitutionRelation, TextType, CollectionType, VocabsBaseClass,
- InstitutionType, ProfessionType, PlaceType, PersonInstitutionRelation, PersonPlaceRelation, PersonPersonRelation,
- VocabNames, InstitutionPlaceRelation, PersonEventRelation,
- PersonWorkRelation, InstitutionEventRelation, InstitutionWorkRelation, PlaceWorkRelation, PlaceEventRelation,
- PlacePlaceRelation, EventWorkRelation, EventEventRelation, WorkWorkRelation, EventType, WorkType)
+ InstitutionInstitutionRelation,
+ TextType,
+ CollectionType,
+ VocabsBaseClass,
+ InstitutionType,
+ ProfessionType,
+ PlaceType,
+ PersonInstitutionRelation,
+ PersonPlaceRelation,
+ PersonPersonRelation,
+ VocabNames,
+ InstitutionPlaceRelation,
+ PersonEventRelation,
+ PersonWorkRelation,
+ InstitutionEventRelation,
+ InstitutionWorkRelation,
+ PlaceWorkRelation,
+ PlaceEventRelation,
+ PlacePlaceRelation,
+ EventWorkRelation,
+ EventEventRelation,
+ WorkWorkRelation,
+ EventType,
+ WorkType,
+)
from .serializers import (
- InstitutionInstitutionRelationSerializer, TextTypeSerializer,
- CollectionTypeSerializer, VocabsBaseClassSerializer,
- InstitutionTypeSerializer, ProfessionTypeSerializer, InstitutionPlaceRelationSerializer,
- PlaceTypeSerializer, PersonInstitutionRelationSerializer,
- PersonPlaceRelationSerializer, UserAccSerializer, VocabNamesSerializer,
- PersonPersonRelationSerializer, PersonEventRelationSerializer, PersonWorkRelationSerializer,
- InstitutionEventRelationSerializer, InstitutionWorkRelationSerializer, PlaceEventRelationSerializer,
- PlaceWorkRelationSerializer, PlacePlaceRelationSerializer, EventWorkRelationSerializer,
- EventEventRelationSerializer, WorkWorkRelationSerializer, EventTypeSerializer, WorkTypeSerializer)
+ InstitutionInstitutionRelationSerializer,
+ TextTypeSerializer,
+ CollectionTypeSerializer,
+ VocabsBaseClassSerializer,
+ InstitutionTypeSerializer,
+ ProfessionTypeSerializer,
+ InstitutionPlaceRelationSerializer,
+ PlaceTypeSerializer,
+ PersonInstitutionRelationSerializer,
+ PersonPlaceRelationSerializer,
+ UserAccSerializer,
+ VocabNamesSerializer,
+ PersonPersonRelationSerializer,
+ PersonEventRelationSerializer,
+ PersonWorkRelationSerializer,
+ InstitutionEventRelationSerializer,
+ InstitutionWorkRelationSerializer,
+ PlaceEventRelationSerializer,
+ PlaceWorkRelationSerializer,
+ PlacePlaceRelationSerializer,
+ EventWorkRelationSerializer,
+ EventEventRelationSerializer,
+ WorkWorkRelationSerializer,
+ EventTypeSerializer,
+ WorkTypeSerializer,
+)
###########################################################
@@ -163,6 +200,3 @@ class EventEventRelationViewSet(viewsets.ModelViewSet):
class WorkWorkRelationViewSet(viewsets.ModelViewSet):
queryset = WorkWorkRelation.objects.all()
serializer_class = WorkWorkRelationSerializer
-
-
-
diff --git a/apis_core/apis_vocabularies/management/commands/basic_rel_vocabs.py b/apis_core/apis_vocabularies/management/commands/basic_rel_vocabs.py
index 5ca42bf..6c080b7 100644
--- a/apis_core/apis_vocabularies/management/commands/basic_rel_vocabs.py
+++ b/apis_core/apis_vocabularies/management/commands/basic_rel_vocabs.py
@@ -7,9 +7,6 @@ class Command(BaseCommand):
help = "creates 'related' vocabs entries for all Relation classes"
def handle(self, *args, **kwargs):
- for x in apps.get_app_config('apis_vocabularies').get_models():
- if x.__name__.endswith('Relation'):
- x.objects.get_or_create(
- name="related",
- name_reverse="related"
- )
+ for x in apps.get_app_config("apis_vocabularies").get_models():
+ if x.__name__.endswith("Relation"):
+ x.objects.get_or_create(name="related", name_reverse="related")
diff --git a/apis_core/apis_vocabularies/management/commands/import_rel_vocabs.py b/apis_core/apis_vocabularies/management/commands/import_rel_vocabs.py
index 4dd8649..22b98e1 100644
--- a/apis_core/apis_vocabularies/management/commands/import_rel_vocabs.py
+++ b/apis_core/apis_vocabularies/management/commands/import_rel_vocabs.py
@@ -24,11 +24,11 @@ class Command(BaseCommand):
help = "creates vocab entries (for relations) stored in the passed in Excel-Sheet"
def add_arguments(self, parser):
- parser.add_argument('data', type=str, help='Location of your Excel-Sheet')
+ parser.add_argument("data", type=str, help="Location of your Excel-Sheet")
# A command must define handle()
def handle(self, *args, **kwargs):
- file = kwargs['data']
+ file = kwargs["data"]
excel_book = pd.read_excel(file, None)
for x in excel_book.keys():
df = pd.read_excel(file, x)
@@ -41,7 +41,7 @@ def handle(self, *args, **kwargs):
if isinstance(row[row_key], str):
temp_item = create_vocab_item(vocab_class, row, row_key)
if c > 1:
- parent_key = "ebene_{}".format(c-1)
+ parent_key = "ebene_{}".format(c - 1)
parent = create_vocab_item(vocab_class, row, parent_key)
temp_item.parent_class = parent
temp_item.save()
diff --git a/apis_core/apis_vocabularies/management/commands/import_wd_professions.py b/apis_core/apis_vocabularies/management/commands/import_wd_professions.py
index c9f331b..6cab346 100644
--- a/apis_core/apis_vocabularies/management/commands/import_wd_professions.py
+++ b/apis_core/apis_vocabularies/management/commands/import_wd_professions.py
@@ -10,13 +10,13 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
- '--lang',
+ "--lang",
default="en",
- help='A two digit language code. Defaults to en',
+ help="A two digit language code. Defaults to en",
)
def handle(self, *args, **options):
- url = 'https://query.wikidata.org/sparql'
+ url = "https://query.wikidata.org/sparql"
query = """
SELECT ?item ?itemLabel ?description
WHERE
@@ -26,23 +26,18 @@ def handle(self, *args, **options):
SERVICE wikibase:label { bd:serviceParam wikibase:language "%s". }
}
"""
- lang = options['lang']
- r = requests.get(url, params={'format': 'json', 'query': query % (lang, lang)})
+ lang = options["lang"]
+ r = requests.get(url, params={"format": "json", "query": query % (lang, lang)})
data = r.json()
data = [
- [
- x['item']['value'],
- x['itemLabel']['value'],
- x['description']['value']
- ] for x in data['results']['bindings']
+ [x["item"]["value"], x["itemLabel"]["value"], x["description"]["value"]]
+ for x in data["results"]["bindings"]
]
for x in data:
- if x[1].startswith('Q') or x[1].startswith('L'):
+ if x[1].startswith("Q") or x[1].startswith("L"):
pass
else:
label = f"{x[1]} ({x[0].split('/')[-1]})"
- item, _ = ProfessionType.objects.get_or_create(
- name=label
- )
+ item, _ = ProfessionType.objects.get_or_create(name=label)
item.description = x[2]
print(item)
diff --git a/apis_core/apis_vocabularies/migrations/0001_initial.py b/apis_core/apis_vocabularies/migrations/0001_initial.py
index 4f0db84..0746394 100644
--- a/apis_core/apis_vocabularies/migrations/0001_initial.py
+++ b/apis_core/apis_vocabularies/migrations/0001_initial.py
@@ -10,287 +10,649 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
- ('apis_entities', '0001_initial'),
- ('apis_relations', '0001_initial'),
- ('apis_metainfo', '0001_initial'),
+ ("apis_entities", "0001_initial"),
+ ("apis_relations", "0001_initial"),
+ ("apis_metainfo", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
- name='VocabNames',
+ name="VocabNames",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('name', models.CharField(max_length=255)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
],
),
migrations.CreateModel(
- name='VocabsBaseClass',
+ name="VocabsBaseClass",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('name', models.CharField(max_length=255, verbose_name='Name')),
- ('description', models.TextField(blank=True, help_text='Brief description of the used term.')),
- ('status', models.CharField(choices=[('rej', 'rejected'), ('ac', 'accepted'), ('can', 'candidate'), ('del', 'deleted')], default='can', max_length=4)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=255, verbose_name="Name")),
+ (
+ "description",
+ models.TextField(
+ blank=True, help_text="Brief description of the used term."
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("rej", "rejected"),
+ ("ac", "accepted"),
+ ("can", "candidate"),
+ ("del", "deleted"),
+ ],
+ default="can",
+ max_length=4,
+ ),
+ ),
],
),
migrations.CreateModel(
- name='VocabsUri',
+ name="VocabsUri",
fields=[
- ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
- ('uri', models.URLField()),
- ('domain', models.CharField(blank=True, max_length=255)),
- ('rdf_link', models.URLField(blank=True)),
- ('loaded', models.BooleanField(default=False)),
- ('loaded_time', models.DateTimeField(blank=True, null=True)),
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("uri", models.URLField()),
+ ("domain", models.CharField(blank=True, max_length=255)),
+ ("rdf_link", models.URLField(blank=True)),
+ ("loaded", models.BooleanField(default=False)),
+ ("loaded_time", models.DateTimeField(blank=True, null=True)),
],
),
migrations.CreateModel(
- name='CollectionType',
+ name="CollectionType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='EventType',
+ name="EventType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='InstitutionType',
+ name="InstitutionType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='LabelType',
+ name="LabelType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='PlaceType',
+ name="PlaceType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='ProfessionType',
+ name="ProfessionType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='RelationBaseClass',
+ name="RelationBaseClass",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
- ('name_reverse', models.CharField(blank=True, help_text='Inverse relation like: "is sub-class of" vs. "is super-class of".', max_length=255, verbose_name='Name reverse')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
+ (
+ "name_reverse",
+ models.CharField(
+ blank=True,
+ help_text='Inverse relation like: "is sub-class of" vs. "is super-class of".',
+ max_length=255,
+ verbose_name="Name reverse",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='TextType',
+ name="TextType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
- ('entity', models.CharField(max_length=255)),
- ('collections', models.ManyToManyField(blank=True, to='apis_metainfo.Collection')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
+ ("entity", models.CharField(max_length=255)),
+ (
+ "collections",
+ models.ManyToManyField(blank=True, to="apis_metainfo.Collection"),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='Title',
+ name="Title",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
- ('abbreviation', models.CharField(blank=True, max_length=10)),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
+ ("abbreviation", models.CharField(blank=True, max_length=10)),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.CreateModel(
- name='WorkType',
+ name="WorkType",
fields=[
- ('vocabsbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.VocabsBaseClass')),
+ (
+ "vocabsbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
+ ),
],
- bases=('apis_vocabularies.vocabsbaseclass',),
+ bases=("apis_vocabularies.vocabsbaseclass",),
),
migrations.AddField(
- model_name='vocabsuri',
- name='vocab',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='apis_vocabularies.VocabsBaseClass'),
+ model_name="vocabsuri",
+ name="vocab",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
),
migrations.AddField(
- model_name='vocabsbaseclass',
- name='parent_class',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='apis_vocabularies.VocabsBaseClass'),
+ model_name="vocabsbaseclass",
+ name="parent_class",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="apis_vocabularies.VocabsBaseClass",
+ ),
),
migrations.AddField(
- model_name='vocabsbaseclass',
- name='userAdded',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
+ model_name="vocabsbaseclass",
+ name="userAdded",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
),
migrations.AddField(
- model_name='vocabsbaseclass',
- name='vocab_name',
- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='apis_vocabularies.VocabNames'),
+ model_name="vocabsbaseclass",
+ name="vocab_name",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to="apis_vocabularies.VocabNames",
+ ),
),
migrations.CreateModel(
- name='EventEventRelation',
+ name="EventEventRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
- ('eventB_set', models.ManyToManyField(blank=True, related_name='eventA_relationtype_set', through='apis_relations.EventEvent', to='apis_entities.Event')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
+ (
+ "eventb_set",
+ models.ManyToManyField(
+ blank=True,
+ related_name="eventa_relationtype_set",
+ through="apis_relations.EventEvent",
+ to="apis_entities.Event",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='EventWorkRelation',
+ name="EventWorkRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='InstitutionEventRelation',
+ name="InstitutionEventRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='InstitutionInstitutionRelation',
+ name="InstitutionInstitutionRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
- ('institutionB_set', models.ManyToManyField(blank=True, related_name='institutionA_relationtype_set', through='apis_relations.InstitutionInstitution', to='apis_entities.Institution')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
+ (
+ "institutionB_set",
+ models.ManyToManyField(
+ blank=True,
+ related_name="institutionA_relationtype_set",
+ through="apis_relations.InstitutionInstitution",
+ to="apis_entities.Institution",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='InstitutionPlaceRelation',
+ name="InstitutionPlaceRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='InstitutionWorkRelation',
+ name="InstitutionWorkRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PersonEventRelation',
+ name="PersonEventRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PersonInstitutionRelation',
+ name="PersonInstitutionRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PersonPersonRelation',
+ name="PersonPersonRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
- ('personB_set', models.ManyToManyField(blank=True, related_name='personA_relationtype_set', through='apis_relations.PersonPerson', to='apis_entities.Person')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
+ (
+ "personB_set",
+ models.ManyToManyField(
+ blank=True,
+ related_name="personA_relationtype_set",
+ through="apis_relations.PersonPerson",
+ to="apis_entities.Person",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PersonPlaceRelation',
+ name="PersonPlaceRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PersonWorkRelation',
+ name="PersonWorkRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PlaceEventRelation',
+ name="PlaceEventRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PlacePlaceRelation',
+ name="PlacePlaceRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
- ('placeB_set', models.ManyToManyField(blank=True, related_name='placeA_relationtype_set', through='apis_relations.PlacePlace', to='apis_entities.Place')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
+ (
+ "placeB_set",
+ models.ManyToManyField(
+ blank=True,
+ related_name="placeA_relationtype_set",
+ through="apis_relations.PlacePlace",
+ to="apis_entities.Place",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='PlaceWorkRelation',
+ name="PlaceWorkRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
migrations.CreateModel(
- name='WorkWorkRelation',
+ name="WorkWorkRelation",
fields=[
- ('relationbaseclass_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='apis_vocabularies.RelationBaseClass')),
- ('workB_set', models.ManyToManyField(blank=True, related_name='workA_relationtype_set', through='apis_relations.WorkWork', to='apis_entities.Work')),
+ (
+ "relationbaseclass_ptr",
+ models.OneToOneField(
+ auto_created=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ parent_link=True,
+ primary_key=True,
+ serialize=False,
+ to="apis_vocabularies.RelationBaseClass",
+ ),
+ ),
+ (
+ "workB_set",
+ models.ManyToManyField(
+ blank=True,
+ related_name="workA_relationtype_set",
+ through="apis_relations.WorkWork",
+ to="apis_entities.Work",
+ ),
+ ),
],
options={
- 'abstract': False,
+ "abstract": False,
},
- bases=('apis_vocabularies.relationbaseclass',),
+ bases=("apis_vocabularies.relationbaseclass",),
),
]
diff --git a/apis_core/apis_vocabularies/migrations/0002_texttype_lang.py b/apis_core/apis_vocabularies/migrations/0002_texttype_lang.py
index b5774d7..f0af51b 100644
--- a/apis_core/apis_vocabularies/migrations/0002_texttype_lang.py
+++ b/apis_core/apis_vocabularies/migrations/0002_texttype_lang.py
@@ -6,13 +6,20 @@
class Migration(migrations.Migration):
dependencies = [
- ('apis_vocabularies', '0001_initial'),
+ ("apis_vocabularies", "0001_initial"),
]
operations = [
migrations.AddField(
- model_name='texttype',
- name='lang',
- field=models.CharField(blank=True, default='deu', help_text="The ISO 639-3 (or 2) code for the label's language.", max_length=3, null=True, verbose_name='ISO Code'),
+ model_name="texttype",
+ name="lang",
+ field=models.CharField(
+ blank=True,
+ default="deu",
+ help_text="The ISO 639-3 (or 2) code for the label's language.",
+ max_length=3,
+ null=True,
+ verbose_name="ISO Code",
+ ),
),
]
diff --git a/apis_core/apis_vocabularies/models.py b/apis_core/apis_vocabularies/models.py
index 776469a..994fd4c 100644
--- a/apis_core/apis_vocabularies/models.py
+++ b/apis_core/apis_vocabularies/models.py
@@ -10,6 +10,7 @@
class VocabNames(models.Model):
"""List of Vocabulary names to allow the easy retrieval\
of Vovcabulary names and classes from the VocabsBaseClass"""
+
name = models.CharField(max_length=255)
def get_vocab_label(self):
@@ -17,27 +18,26 @@ def get_vocab_label(self):
class VocabsBaseClass(models.Model):
- """ An abstract base class for other classes which contain so called
+ """An abstract base class for other classes which contain so called
'controlled vocabulary' to describe subtypes of main temporalized
entites"""
+
choices_status = (
- ('rej', 'rejected'),
- ('ac', 'accepted'),
- ('can', 'candidate'),
- ('del', 'deleted')
+ ("rej", "rejected"),
+ ("ac", "accepted"),
+ ("can", "candidate"),
+ ("del", "deleted"),
)
- name = models.CharField(max_length=255, verbose_name='Name')
+ name = models.CharField(max_length=255, verbose_name="Name")
description = models.TextField(
- blank=True,
- help_text="Brief description of the used term.")
+ blank=True, help_text="Brief description of the used term."
+ )
parent_class = models.ForeignKey(
- 'self', blank=True, null=True,
- on_delete=models.CASCADE
+ "self", blank=True, null=True, on_delete=models.CASCADE
)
- status = models.CharField(max_length=4, choices=choices_status, default='can')
+ status = models.CharField(max_length=4, choices=choices_status, default="can")
vocab_name = models.ForeignKey(
- VocabNames, blank=True, null=True,
- on_delete=models.SET_NULL
+ VocabNames, blank=True, null=True, on_delete=models.SET_NULL
)
def __str__(self):
@@ -46,8 +46,10 @@ def __str__(self):
def save(self, *args, **kwargs):
d, created = VocabNames.objects.get_or_create(name=type(self).__name__)
self.vocab_name = d
- if self.name != unicodedata.normalize('NFC', self.name): # secure correct unicode encoding
- self.name = unicodedata.normalize('NFC', self.name)
+ if self.name != unicodedata.normalize(
+ "NFC", self.name
+ ): # secure correct unicode encoding
+ self.name = unicodedata.normalize("NFC", self.name)
super(VocabsBaseClass, self).save(*args, **kwargs)
return self
@@ -56,21 +58,22 @@ def label(self):
d = self
res = self.name
while d.parent_class:
- res = d.parent_class.name + ' >> ' + res
+ res = d.parent_class.name + " >> " + res
d = d.parent_class
return res
class RelationBaseClass(VocabsBaseClass):
- """ An abstract base class for other classes which contain so called
+ """An abstract base class for other classes which contain so called
'controlled vocabulary' to describe the relations between main temporalized
entities ('db_')"""
name_reverse = models.CharField(
max_length=255,
- verbose_name='Name reverse',
+ verbose_name="Name reverse",
help_text='Inverse relation like: "is sub-class of" vs. "is super-class of".',
- blank=True)
+ blank=True,
+ )
def __str__(self):
return self.name
@@ -79,23 +82,23 @@ def __str__(self):
def label_reverse(self):
d = self
if len(self.name_reverse) < 1:
- res = '(' + self.name + ')'
+ res = "(" + self.name + ")"
else:
res = self.name_reverse
while d.parent_class:
try:
t = RelationBaseClass.objects.get(pk=d.parent_class.pk).name_reverse
if len(t) < 1:
- t = '(' + d.parent_class.name + ')'
+ t = "(" + d.parent_class.name + ")"
except Exception as e:
- t = '(' + d.parent_class.name + ')'
- res = t + ' >> ' + res
+ t = "(" + d.parent_class.name + ")"
+ res = t + " >> " + res
d = d.parent_class
return res
def save(self, *args, **kwargs):
- if self.name_reverse != unicodedata.normalize('NFC', self.name_reverse):
- self.name_reverse = unicodedata.normalize('NFC', self.name_reverse)
+ if self.name_reverse != unicodedata.normalize("NFC", self.name_reverse):
+ self.name_reverse = unicodedata.normalize("NFC", self.name_reverse)
if self.name_reverse == "" or self.name_reverse == None:
self.name_reverse = self.name + " [REVERSE]"
@@ -108,11 +111,13 @@ class VocabsUri(models.Model):
"""Class to store URIs for imported types. URI class from metainfo is not
used in order to keep the vocabularies module/app seperated from the rest of the application.
"""
+
uri = models.URLField()
domain = models.CharField(max_length=255, blank=True)
rdf_link = models.URLField(blank=True)
- vocab = models.ForeignKey(VocabsBaseClass, blank=True, null=True,
- on_delete=models.CASCADE)
+ vocab = models.ForeignKey(
+ VocabsBaseClass, blank=True, null=True, on_delete=models.CASCADE
+ )
# loaded: set to True when RDF was loaded and parsed into the data model
loaded = models.BooleanField(default=False)
# loaded_time: Timestamp when file was loaded and parsed
@@ -121,6 +126,7 @@ class VocabsUri(models.Model):
def __str__(self):
return self.uri
+
#######################################################################
#
# entity types
@@ -130,52 +136,65 @@ def __str__(self):
class WorkType(VocabsBaseClass):
"""Holds controlled vocabularies about work-types"""
+
pass
class Title(VocabsBaseClass):
"""A person´s (academic) title"""
+
abbreviation = models.CharField(max_length=10, blank=True)
class ProfessionType(VocabsBaseClass):
"""Holds controlled vocabularies about profession-types"""
+
pass
class PlaceType(VocabsBaseClass):
"""Holds controlled vocabularies about place-types"""
+
pass
class InstitutionType(VocabsBaseClass):
"""Holds controlled vocabularies about institution-types"""
+
pass
class EventType(VocabsBaseClass):
"""Holds controlled vocabularies about event-types"""
+
pass
class LabelType(VocabsBaseClass):
"""Holds controlled vocabularies about label-types"""
+
pass
class CollectionType(VocabsBaseClass):
- """e.g. reseachCollection, importCollection """
+ """e.g. reseachCollection, importCollection"""
+
pass
+
class TextType(VocabsBaseClass):
"""used to store the Text types for the forms"""
+
entity = models.CharField(max_length=255)
- collections = models.ManyToManyField('apis_metainfo.Collection', blank=True)
+ collections = models.ManyToManyField("apis_metainfo.Collection", blank=True)
lang = models.CharField(
- max_length=3, blank=True, null=True,
+ max_length=3,
+ blank=True,
+ null=True,
help_text="The ISO 639-3 (or 2) code for the label's language.",
- verbose_name='ISO Code', default='deu')
-
+ verbose_name="ISO Code",
+ default="deu",
+ )
#######################################################################
@@ -185,7 +204,6 @@ class TextType(VocabsBaseClass):
#######################################################################
-
class AbstractRelationType(RelationBaseClass):
"""
Abstract super class which encapsulates common logic between the different relationtypes and provides various methods
@@ -199,14 +217,13 @@ class Meta:
_all_relationtype_names = None
_related_entity_field_names = None
-
# Methods dealing with all relationtypes
####################################################################################################################
-
+
@classmethod
def get_all_relationtype_classes(cls):
"""
- :return: list of all python classes of the relationtypes defined within this models' module
+ :return: list of all python classes of the relationtypes defined within this models' module
"""
if cls._all_relationtype_classes == None:
@@ -215,11 +232,15 @@ def get_all_relationtype_classes(cls):
relationtype_names = []
for relationtype_name, relationtype_class in inspect.getmembers(
- sys.modules[__name__], inspect.isclass):
+ sys.modules[__name__], inspect.isclass
+ ):
- if relationtype_class.__module__ == "apis_core.apis_vocabularies.models" and \
- relationtype_name != "ent_class" and \
- relationtype_name.endswith("Relation"):
+ if (
+ relationtype_class.__module__
+ == "apis_core.apis_vocabularies.models"
+ and relationtype_name != "ent_class"
+ and relationtype_name.endswith("Relation")
+ ):
relationtype_classes.append(relationtype_class)
relationtype_names.append(relationtype_name.lower())
@@ -229,7 +250,6 @@ def get_all_relationtype_classes(cls):
return cls._all_relationtype_classes
-
@classmethod
def get_relationtype_class_of_name(cls, relationtype_name):
"""
@@ -243,7 +263,6 @@ def get_relationtype_class_of_name(cls, relationtype_name):
raise Exception("Could not find relationtype class of name:", relationtype_name)
-
@classmethod
def get_all_relationtype_names(cls):
"""
@@ -256,10 +275,9 @@ def get_all_relationtype_names(cls):
return cls._all_relationtype_names
-
# Methods dealing with related entities
####################################################################################################################
-
+
@classmethod
def get_related_entity_field_names(cls):
"""
@@ -277,7 +295,6 @@ def get_related_entity_field_names(cls):
else:
return cls._related_entity_field_names
-
@classmethod
def add_related_entity_field_name(cls, entity_field_name):
"""
@@ -301,26 +318,31 @@ def add_related_entity_field_name(cls, entity_field_name):
class PersonPersonRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Persons and Persons"""
+
pass
class PersonPlaceRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Persons and Places"""
+
pass
class PersonInstitutionRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Persons and Persons"""
+
pass
class PersonEventRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Persons and Events"""
+
pass
class PersonWorkRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Persons and Works"""
+
pass
@@ -331,23 +353,28 @@ class PersonWorkRelation(AbstractRelationType):
class InstitutionEventRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Institutions and Events."""
+
pass
class InstitutionPlaceRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Institutions and Places."""
+
pass
class InstitutionInstitutionRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Institutions and Institutions."""
+
pass
class InstitutionWorkRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Institutions and Works."""
+
pass
+
#######################################################################
# Place-Relation-Types
#######################################################################
@@ -355,16 +382,19 @@ class InstitutionWorkRelation(AbstractRelationType):
class PlacePlaceRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Places and Places"""
+
pass
class PlaceEventRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Places and Events"""
+
pass
class PlaceWorkRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Places and Works"""
+
pass
@@ -375,11 +405,13 @@ class PlaceWorkRelation(AbstractRelationType):
class EventEventRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Events and Events"""
+
pass
class EventWorkRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Events and Works"""
+
pass
@@ -390,6 +422,5 @@ class EventWorkRelation(AbstractRelationType):
class WorkWorkRelation(AbstractRelationType):
"""Holds controlled vocabularies relation types of Works and Works"""
- pass
-
+ pass
diff --git a/apis_core/apis_vocabularies/serializers.py b/apis_core/apis_vocabularies/serializers.py
index 1fc4d34..a794066 100644
--- a/apis_core/apis_vocabularies/serializers.py
+++ b/apis_core/apis_vocabularies/serializers.py
@@ -3,11 +3,32 @@
from rest_framework import serializers
from .models import (
- InstitutionInstitutionRelation, TextType, CollectionType, VocabsBaseClass,
- InstitutionType, ProfessionType, PlaceType, PersonInstitutionRelation, InstitutionPlaceRelation,
- PersonPlaceRelation, VocabNames, PersonPersonRelation, PersonEventRelation, PersonWorkRelation,
- InstitutionEventRelation, InstitutionWorkRelation, PlaceEventRelation, PlaceWorkRelation, PlacePlaceRelation,
- EventWorkRelation, EventEventRelation, WorkWorkRelation, EventType, WorkType, LabelType)
+ InstitutionInstitutionRelation,
+ TextType,
+ CollectionType,
+ VocabsBaseClass,
+ InstitutionType,
+ ProfessionType,
+ PlaceType,
+ PersonInstitutionRelation,
+ InstitutionPlaceRelation,
+ PersonPlaceRelation,
+ VocabNames,
+ PersonPersonRelation,
+ PersonEventRelation,
+ PersonWorkRelation,
+ InstitutionEventRelation,
+ InstitutionWorkRelation,
+ PlaceEventRelation,
+ PlaceWorkRelation,
+ PlacePlaceRelation,
+ EventWorkRelation,
+ EventEventRelation,
+ WorkWorkRelation,
+ EventType,
+ WorkType,
+ LabelType,
+)
###########################################################
@@ -46,8 +67,9 @@ def __init__(self, *args, **kwargs):
else:
rt = self.instance
if "Relation" in rt.__class__.__name__:
- self.fields['name_reverse'] = serializers.CharField()
- self.fields['label_reverse'] = serializers.CharField()
+ self.fields["name_reverse"] = serializers.CharField()
+ self.fields["label_reverse"] = serializers.CharField()
+
###########################################################
#
@@ -57,56 +79,48 @@ def __init__(self, *args, **kwargs):
class UserAccSerializer(serializers.ModelSerializer):
-
class Meta:
model = User
- fields = ['username', 'email']
+ fields = ["username", "email"]
class VocabsBaseSerializer(serializers.HyperlinkedModelSerializer):
userAdded = serializers.HyperlinkedRelatedField(
- view_name="apis:apis_api:user-detail",
- lookup_field="pk",
- read_only=True
+ view_name="apis:apis_api:user-detail", lookup_field="pk", read_only=True
)
parent_class = serializers.HyperlinkedRelatedField(
view_name="apis:apis_api:vocabsbaseclass-detail",
lookup_field="pk",
- read_only=True
+ read_only=True,
)
vocab_name = serializers.HyperlinkedRelatedField(
- view_name="apis:apis_api:vocabnames-detail",
- lookup_field="pk",
- read_only=True
+ view_name="apis:apis_api:vocabnames-detail", lookup_field="pk", read_only=True
)
class CollectionTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:collectiontype-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:collectiontype-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = CollectionType
class VocabsBaseClassSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:vocabsbaseclass-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:vocabsbaseclass-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = VocabsBaseClass
class VocabNamesSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = VocabNames
@@ -119,82 +133,76 @@ class Meta:
class TextTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:texttype-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:texttype-detail", lookup_field="pk"
)
collections = serializers.HyperlinkedRelatedField(
view_name="apis:apis_api:collection-detail",
lookup_field="pk",
many=True,
- read_only=True
+ read_only=True,
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = TextType
class InstitutionTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:institutiontype-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:institutiontype-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionType
class ProfessionTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:profession-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:profession-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = ProfessionType
class PlaceTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:placetype-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:placetype-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlaceType
class EventTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:eventtype-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:eventtype-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = EventType
class WorkTypeSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:worktype-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:worktype-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = WorkType
class LabelTypeMinimalSerializer(serializers.ModelSerializer):
-
class Meta:
- fields = ('id', 'name')
+ fields = ("id", "name")
model = LabelType
+
#####################################################################
#
# Relations
@@ -203,110 +211,95 @@ class Meta:
class InstitutionInstitutionRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionInstitutionRelation
class PersonPersonRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonPersonRelation
class PersonInstitutionRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonInstitutionRelation
class PersonPlaceRelationSerializer(VocabsBaseSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name="apis:apis_api:personplacerelation-detail",
- lookup_field="pk"
+ view_name="apis:apis_api:personplacerelation-detail", lookup_field="pk"
)
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonPlaceRelation
class PersonEventRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonEventRelation
class PersonWorkRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PersonWorkRelation
class InstitutionPlaceRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionPlaceRelation
class InstitutionEventRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionEventRelation
class InstitutionWorkRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = InstitutionWorkRelation
class PlaceEventRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlaceEventRelation
class PlaceWorkRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlaceWorkRelation
class PlacePlaceRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = PlacePlaceRelation
class EventWorkRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = EventWorkRelation
class EventEventRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = EventEventRelation
class WorkWorkRelationSerializer(VocabsBaseSerializer):
-
class Meta:
- fields = '__all__'
+ fields = "__all__"
model = WorkWorkRelation
diff --git a/apis_core/apis_vocabularies/urls.py b/apis_core/apis_vocabularies/urls.py
index a5c07ac..e840527 100644
--- a/apis_core/apis_vocabularies/urls.py
+++ b/apis_core/apis_vocabularies/urls.py
@@ -7,7 +7,8 @@
urlpatterns = [
path("download//", views.dl_vocabs_as_csv, name="dl-vocabs"),
- path("autocomplete///",
+ path(
+ "autocomplete///",
GenericVocabulariesAutocomplete.as_view(),
name="generic_vocabularies_autocomplete",
),
diff --git a/apis_core/apis_vocabularies/views.py b/apis_core/apis_vocabularies/views.py
index 7e1bd38..ad1dc9c 100644
--- a/apis_core/apis_vocabularies/views.py
+++ b/apis_core/apis_vocabularies/views.py
@@ -6,22 +6,20 @@
@login_required
def dl_vocabs_as_csv(request, model_name):
- kwargs = {
- "app_label": "apis_vocabularies",
- "entity": model_name
- }
+ kwargs = {"app_label": "apis_vocabularies", "entity": model_name}
model = ContentType.objects.get(
app_label=kwargs.get("app_label"), model=kwargs.get("entity").lower()
).model_class()
data = [[x.id, x.name, x.parent_class] for x in model.objects.all()]
- columns = ['id', 'name', 'parent_class']
+ columns = ["id", "name", "parent_class"]
df = pd.DataFrame(data, columns=columns)
filename = f"{kwargs.get('entity').lower()}.csv"
# Create the HttpResponse object with the appropriate CSV header.
- response = HttpResponse(content_type='text/csv')
- response['Content-Disposition'] = f"attachment; filename='{filename}'"
+ response = HttpResponse(content_type="text/csv")
+ response["Content-Disposition"] = f"attachment; filename='{filename}'"
df.to_csv(response, index=False)
return response
+
# Create your views here.
diff --git a/apis_core/context_processors/custom_context_processors.py b/apis_core/context_processors/custom_context_processors.py
index c814439..21a9799 100644
--- a/apis_core/context_processors/custom_context_processors.py
+++ b/apis_core/context_processors/custom_context_processors.py
@@ -7,43 +7,47 @@
def add_entities(request):
ent_list = []
for name, obj in inspect.getmembers(
- sys.modules['apis_core.apis_entities.models'], inspect.isclass
+ sys.modules["apis_core.apis_entities.models"], inspect.isclass
):
- if obj.__module__ == 'apis_core.apis_entities.models' and name != "AbstractEntity" and name != "ent_class":
+ if (
+ obj.__module__ == "apis_core.apis_entities.models"
+ and name != "AbstractEntity"
+ and name != "ent_class"
+ ):
ent_list.append(str(name).lower())
- res = {
- 'entities_list': ent_list,
- 'request': request
- }
+ res = {"entities_list": ent_list, "request": request}
return res
def add_relations(request):
relations_list = []
for name, obj in inspect.getmembers(
- sys.modules['apis_core.apis_relations.models'], inspect.isclass
+ sys.modules["apis_core.apis_relations.models"], inspect.isclass
):
- if obj.__module__ == 'apis_core.apis_relations.models' and name not in ["AbstractRelation", "AnnotationRelationLinkManager", "ent_class", "BaseRelationManager", "RelationPublishedQueryset"]:
+ if obj.__module__ == "apis_core.apis_relations.models" and name not in [
+ "AbstractRelation",
+ "AnnotationRelationLinkManager",
+ "ent_class",
+ "BaseRelationManager",
+ "RelationPublishedQueryset",
+ ]:
relations_list.append(str(name).lower())
- res = {
- 'relations_list': relations_list,
- 'request': request
- }
+ res = {"relations_list": relations_list, "request": request}
return res
def add_apis_settings(request):
"""adds the custom settings to the templates"""
res = {
- 'additional_functions': getattr(settings, "APIS_COMPONENTS", []),
- 'request': request
+ "additional_functions": getattr(settings, "APIS_COMPONENTS", []),
+ "request": request,
}
- if 'apis_highlighter' in settings.INSTALLED_APPS:
- res['highlighter_active'] = True
+ if "apis_highlighter" in settings.INSTALLED_APPS:
+ res["highlighter_active"] = True
else:
- res['highlighter_active'] = False
- if 'apis_bibsonomy' in settings.INSTALLED_APPS:
- res['bibsonomy_active'] = True
+ res["highlighter_active"] = False
+ if "apis_bibsonomy" in settings.INSTALLED_APPS:
+ res["bibsonomy_active"] = True
else:
- res['bibsonomy_active'] = False
+ res["bibsonomy_active"] = False
return res
diff --git a/apis_core/default_settings/NER_settings.py b/apis_core/default_settings/NER_settings.py
index 5d93760..678d815 100644
--- a/apis_core/default_settings/NER_settings.py
+++ b/apis_core/default_settings/NER_settings.py
@@ -2,172 +2,305 @@
# -*- coding: utf-8 -*-
gn = "http://www.geonames.org/ontology#"
-stb_base = 'https://enrich.acdh.oeaw.ac.at/entityhub/site/'
+stb_base = "https://enrich.acdh.oeaw.ac.at/entityhub/site/"
URL_geonames = stb_base + "geoNames_%s/query"
wgs84_pos = "http://www.w3.org/2003/01/geo/wgs84_pos#"
gnd_geo = "http://www.opengis.net/ont/geosparql#"
-stb_find = stb_base + u'{}/find'
-GenderMappingGND = {'male': 'http://d-nb.info/standards/vocab/gnd/Gender#male',
- 'männlich': 'http://d-nb.info/standards/vocab/gnd/Gender#male',
- 'Mann': 'http://d-nb.info/standards/vocab/gnd/Gender#male',
- 'female': 'http://d-nb.info/standards/vocab/gnd/Gender#female',
- 'weiblich': 'http://d-nb.info/standards/vocab/gnd/Gender#female',
- 'Frau': 'http://d-nb.info/standards/vocab/gnd/Gender#female'}
+stb_find = stb_base + "{}/find"
+GenderMappingGND = {
+ "male": "http://d-nb.info/standards/vocab/gnd/Gender#male",
+ "männlich": "http://d-nb.info/standards/vocab/gnd/Gender#male",
+ "Mann": "http://d-nb.info/standards/vocab/gnd/Gender#male",
+ "female": "http://d-nb.info/standards/vocab/gnd/Gender#female",
+ "weiblich": "http://d-nb.info/standards/vocab/gnd/Gender#female",
+ "Frau": "http://d-nb.info/standards/vocab/gnd/Gender#female",
+}
+
def date_conversion(date):
return "{}T00:00:00.000Z".format(date)
+
autocomp_settings = {
- 'score': u'http://stanbol.apache.org/ontology/entityhub/query#score',
- 'uri': 'id',
- 'label': u'http://www.w3.org/2000/01/rdf-schema#label',
- 'Place': [
- {'source': 'Geonames',
- 'type': False,
- 'url': stb_find.format('geoNames_S_P_A'),
- 'fields': {
- 'descr': (gn + 'featureCode', 'String'),
- 'name': (gn + 'name','String'),
- 'long': (wgs84_pos + 'long', 'String'),
- 'lat': (wgs84_pos + 'lat', 'String')
- }},
- {'source': 'GeonamesRGN',
- 'type': False,
- 'url': stb_find.format('geoNames_RGN'),
- 'fields': {
- 'descr': (gn + 'featureCode','String'),
- 'name': (gn + 'name','String'),
- 'long': (wgs84_pos + 'long','String'),
- 'lat': (wgs84_pos + 'lat','String')
- }},
- {'source': 'GeonamesVAL',
- 'type': False,
- 'url': stb_find.format('geoNames_VAL'),
- 'fields': {
- 'descr': (gn + 'featureCode','String'),
- 'name': (gn + 'name','String'),
- 'long': (wgs84_pos + 'long','String'),
- 'lat': (wgs84_pos + 'lat','String')
- }},
- {'source': 'GND',
- 'type': u'http://d-nb.info/standards/elementset/gnd#TerritorialCorporateBodyOrAdministrativeUnit',
- 'url': stb_find.format('gndTerritorialCorporateBodyOrAdministrativeUnits'),
- 'fields': {
- 'name': (u'http://d-nb.info/standards/elementset/gnd#preferredNameForThePlaceOrGeographicName','String'),
- 'descr': (u'http://d-nb.info/standards/elementset/gnd#definition','String'),
- 'long': (gnd_geo + 'asWKT', 'gndLong'),
- 'lat': (wgs84_pos + 'lat','String')
- }},
- ],
- 'Institution': [{
- 'source': 'GND',
- 'type': u'http://d-nb.info/standards/elementset/gnd#CorporateBody',
- 'url': stb_find.format('gndCorporateBodyAndOrganOfCorporateBody'),
- 'fields': {
- 'descr': (u'http://d-nb.info/standards/elementset/gnd#definition','String'),
- 'name': (u'http://d-nb.info/standards/elementset/gnd#preferredNameForTheCorporateBody','String')}},
- {
- 'source': 'GND',
- 'type': u'http://d-nb.info/standards/elementset/gnd#OrganOfCorporateBody',
- 'url': stb_find.format('gndCorporateBodyAndOrganOfCorporateBody'),
- 'fields': {
- 'descr': (u'http://d-nb.info/standards/elementset/gnd#definition','String'),
- 'name': (u'http://d-nb.info/standards/elementset/gnd#preferredNameForTheCorporateBody','String')}}],
- 'Person': [{
- 'source': 'GND',
- 'type': u'http://d-nb.info/standards/elementset/gnd#DifferentiatedPerson',
- 'url': stb_find.format('gndPersons'),
- 'search fields': {'gender': ('http://d-nb.info/standards/elementset/gnd#gender',
- GenderMappingGND, 'reference'),
- 'start_date': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_exact'),
- 'end_date': ('http://d-nb.info/standards/elementset/gnd#dateOfDeath',
- date_conversion, 'date_exact'),
- 'start_date__gt': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_gt'),
- 'start_date__lt': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_lt'),
- 'end_date__gt': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_gt'),
- 'end_date__lt': ('http://d-nb.info/standards/elementset/gnd#dateOfDeath',
- date_conversion, 'date_lt')},
- 'fields': {
- 'descr': (u'http://d-nb.info/standards/elementset/gnd#biographicalOrHistoricalInformation','String'),
- 'name': (u'http://d-nb.info/standards/elementset/gnd#preferredNameForThePerson','String'),
- 'dateOfBirth': (u'http://d-nb.info/standards/elementset/gnd#dateOfBirth', 'GNDDate'),
- 'dateOfDeath': (u'http://d-nb.info/standards/elementset/gnd#dateOfDeath', 'GNDDate')}},
-{
- 'source': 'GND',
- 'type': u'http://enrich.acdh.oeaw.ac.at/stanbol/entityhub/site/gndRoyalOrMemberOfARoyalHouse/',
- 'url': stb_find.format('gndRoyalOrMemberOfARoyalHouse'),
- 'search fields': {'gender': ('http://d-nb.info/standards/elementset/gnd#gender',
- GenderMappingGND, 'reference'),
- 'start_date': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_exact'),
- 'end_date': ('http://d-nb.info/standards/elementset/gnd#dateOfDeath',
- date_conversion, 'date_exact'),
- 'start_date__gt': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_gt'),
- 'start_date__lt': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_lt'),
- 'end_date__gt': ('http://d-nb.info/standards/elementset/gnd#dateOfBirth',
- date_conversion, 'date_gt'),
- 'end_date__lt': ('http://d-nb.info/standards/elementset/gnd#dateOfDeath',
- date_conversion, 'date_lt')},
- 'fields': {
- 'descr': (u'http://d-nb.info/standards/elementset/gnd#biographicalOrHistoricalInformation','String'),
- 'name': (u'http://d-nb.info/standards/elementset/gnd#preferredNameForThePerson','String'),
- 'dateOfBirth': (u'http://d-nb.info/standards/elementset/gnd#dateOfBirth', 'GNDDate'),
- 'dateOfDeath': (u'http://d-nb.info/standards/elementset/gnd#dateOfDeath', 'GNDDate')}}
+ "score": "http://stanbol.apache.org/ontology/entityhub/query#score",
+ "uri": "id",
+ "label": "http://www.w3.org/2000/01/rdf-schema#label",
+ "Place": [
+ {
+ "source": "Geonames",
+ "type": False,
+ "url": stb_find.format("geoNames_S_P_A"),
+ "fields": {
+ "descr": (gn + "featureCode", "String"),
+ "name": (gn + "name", "String"),
+ "long": (wgs84_pos + "long", "String"),
+ "lat": (wgs84_pos + "lat", "String"),
+ },
+ },
+ {
+ "source": "GeonamesRGN",
+ "type": False,
+ "url": stb_find.format("geoNames_RGN"),
+ "fields": {
+ "descr": (gn + "featureCode", "String"),
+ "name": (gn + "name", "String"),
+ "long": (wgs84_pos + "long", "String"),
+ "lat": (wgs84_pos + "lat", "String"),
+ },
+ },
+ {
+ "source": "GeonamesVAL",
+ "type": False,
+ "url": stb_find.format("geoNames_VAL"),
+ "fields": {
+ "descr": (gn + "featureCode", "String"),
+ "name": (gn + "name", "String"),
+ "long": (wgs84_pos + "long", "String"),
+ "lat": (wgs84_pos + "lat", "String"),
+ },
+ },
+ {
+ "source": "GND",
+ "type": "http://d-nb.info/standards/elementset/gnd#TerritorialCorporateBodyOrAdministrativeUnit",
+ "url": stb_find.format("gndTerritorialCorporateBodyOrAdministrativeUnits"),
+ "fields": {
+ "name": (
+ "http://d-nb.info/standards/elementset/gnd#preferredNameForThePlaceOrGeographicName",
+ "String",
+ ),
+ "descr": (
+ "http://d-nb.info/standards/elementset/gnd#definition",
+ "String",
+ ),
+ "long": (gnd_geo + "asWKT", "gndLong"),
+ "lat": (wgs84_pos + "lat", "String"),
+ },
+ },
+ ],
+ "Institution": [
+ {
+ "source": "GND",
+ "type": "http://d-nb.info/standards/elementset/gnd#CorporateBody",
+ "url": stb_find.format("gndCorporateBodyAndOrganOfCorporateBody"),
+ "fields": {
+ "descr": (
+ "http://d-nb.info/standards/elementset/gnd#definition",
+ "String",
+ ),
+ "name": (
+ "http://d-nb.info/standards/elementset/gnd#preferredNameForTheCorporateBody",
+ "String",
+ ),
+ },
+ },
+ {
+ "source": "GND",
+ "type": "http://d-nb.info/standards/elementset/gnd#OrganOfCorporateBody",
+ "url": stb_find.format("gndCorporateBodyAndOrganOfCorporateBody"),
+ "fields": {
+ "descr": (
+ "http://d-nb.info/standards/elementset/gnd#definition",
+ "String",
+ ),
+ "name": (
+ "http://d-nb.info/standards/elementset/gnd#preferredNameForTheCorporateBody",
+ "String",
+ ),
+ },
+ },
+ ],
+ "Person": [
+ {
+ "source": "GND",
+ "type": "http://d-nb.info/standards/elementset/gnd#DifferentiatedPerson",
+ "url": stb_find.format("gndPersons"),
+ "search fields": {
+ "gender": (
+ "http://d-nb.info/standards/elementset/gnd#gender",
+ GenderMappingGND,
+ "reference",
+ ),
+ "start_date": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_exact",
+ ),
+ "end_date": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfDeath",
+ date_conversion,
+ "date_exact",
+ ),
+ "start_date__gt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_gt",
+ ),
+ "start_date__lt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_lt",
+ ),
+ "end_date__gt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_gt",
+ ),
+ "end_date__lt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfDeath",
+ date_conversion,
+ "date_lt",
+ ),
+ },
+ "fields": {
+ "descr": (
+ "http://d-nb.info/standards/elementset/gnd#biographicalOrHistoricalInformation",
+ "String",
+ ),
+ "name": (
+ "http://d-nb.info/standards/elementset/gnd#preferredNameForThePerson",
+ "String",
+ ),
+ "dateOfBirth": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ "GNDDate",
+ ),
+ "dateOfDeath": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfDeath",
+ "GNDDate",
+ ),
+ },
+ },
+ {
+ "source": "GND",
+ "type": "http://enrich.acdh.oeaw.ac.at/stanbol/entityhub/site/gndRoyalOrMemberOfARoyalHouse/",
+ "url": stb_find.format("gndRoyalOrMemberOfARoyalHouse"),
+ "search fields": {
+ "gender": (
+ "http://d-nb.info/standards/elementset/gnd#gender",
+ GenderMappingGND,
+ "reference",
+ ),
+ "start_date": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_exact",
+ ),
+ "end_date": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfDeath",
+ date_conversion,
+ "date_exact",
+ ),
+ "start_date__gt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_gt",
+ ),
+ "start_date__lt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_lt",
+ ),
+ "end_date__gt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ date_conversion,
+ "date_gt",
+ ),
+ "end_date__lt": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfDeath",
+ date_conversion,
+ "date_lt",
+ ),
+ },
+ "fields": {
+ "descr": (
+ "http://d-nb.info/standards/elementset/gnd#biographicalOrHistoricalInformation",
+ "String",
+ ),
+ "name": (
+ "http://d-nb.info/standards/elementset/gnd#preferredNameForThePerson",
+ "String",
+ ),
+ "dateOfBirth": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfBirth",
+ "GNDDate",
+ ),
+ "dateOfDeath": (
+ "http://d-nb.info/standards/elementset/gnd#dateOfDeath",
+ "GNDDate",
+ ),
+ },
+ },
+ ],
+ "Event": [
+ {
+ "source": "GND",
+ "type": "http://d-nb.info/standards/elementset/gnd#HistoricSingleEventOrEra",
+ "url": stb_find.format("gndHistoricEvent"),
+ "fields": {
+ "descr": (
+ "http://d-nb.info/standards/elementset/gnd#definition",
+ "String",
+ ),
+ "name": (
+ "http://d-nb.info/standards/elementset/gnd#preferredNameForTheSubjectHeading",
+ "String",
+ ),
+ },
+ }
],
- 'Event': [{
- 'source': 'GND',
- 'type': u'http://d-nb.info/standards/elementset/gnd#HistoricSingleEventOrEra',
- 'url': stb_find.format('gndHistoricEvent'),
- 'fields': {
- 'descr': (u'http://d-nb.info/standards/elementset/gnd#definition','String'),
- 'name': (u'http://d-nb.info/standards/elementset/gnd#preferredNameForTheSubjectHeading','String')}}],
- 'Work': []
+ "Work": [],
}
geonames_feature_codes = {
"ADM1": (
"first-order administrative division",
- "a primary administrative division of a country, such as a state in the United States"),
+ "a primary administrative division of a country, such as a state in the United States",
+ ),
"ADM1H": (
"historical first-order administrative division",
- "a former first-order administrative division"),
+ "a former first-order administrative division",
+ ),
"ADM2": (
"second-order administrative division",
- "a subdivision of a first-order administrative division"),
+ "a subdivision of a first-order administrative division",
+ ),
"ADM2H": (
"historical second-order administrative division",
- "a former second-order administrative division"),
+ "a former second-order administrative division",
+ ),
"ADM3": (
"third-order administrative division",
- "a subdivision of a second-order administrative division"),
+ "a subdivision of a second-order administrative division",
+ ),
"ADM3H": (
"historical third-order administrative division",
- "a former third-order administrative division"),
+ "a former third-order administrative division",
+ ),
"ADM4": (
"fourth-order administrative division",
- "a subdivision of a third-order administrative division"),
+ "a subdivision of a third-order administrative division",
+ ),
"ADM4H": (
"historical fourth-order administrative division",
- "a former fourth-order administrative division"),
+ "a former fourth-order administrative division",
+ ),
"ADM5": (
"fifth-order administrative division",
- "a subdivision of a fourth-order administrative division"),
+ "a subdivision of a fourth-order administrative division",
+ ),
"ADMD": (
"administrative division",
- "an administrative division of a country, undifferentiated as to administrative level"),
+ "an administrative division of a country, undifferentiated as to administrative level",
+ ),
"ADMDH": (
"historical administrative division",
"a former administrative division of a political entity, \
- undifferentiated as to administrative level"),
+ undifferentiated as to administrative level",
+ ),
"LTER": (
"leased area",
- "a tract of land leased to another country, usually for military installations"),
+ "a tract of land leased to another country, usually for military installations",
+ ),
"PCL": ("political entity", ""),
"PCLD": ("dependent political entity", ""),
"PCLF": ("freely associated state", ""),
@@ -181,147 +314,143 @@ def date_conversion(date):
"ZNB": (
"buffer zone",
"a zone recognized as a buffer between two nations in which \
- military presence is minimal or absent"),
+ military presence is minimal or absent",
+ ),
"PPL": (
"populated place",
- "a city, town, village, or other agglomeration of buildings where people live and work"),
+ "a city, town, village, or other agglomeration of buildings where people live and work",
+ ),
"PPLA": (
"seat of a first-order administrative division",
- "seat of a first-order administrative division (PPLC takes precedence over PPLA),"),
+ "seat of a first-order administrative division (PPLC takes precedence over PPLA),",
+ ),
"PPLA2": ("seat of a second-order administrative division", ""),
"PPLA3": ("seat of a third-order administrative division", ""),
"PPLA4": ("seat of a fourth-order administrative division", ""),
"PPLC": ("capital of a political entity", ""),
"PPLCH": (
"historical capital of a political entity",
- "a former capital of a political entity"),
+ "a former capital of a political entity",
+ ),
"PPLF": (
"farm village",
- "a populated place where the population is largely engaged in agricultural activities"),
+ "a populated place where the population is largely engaged in agricultural activities",
+ ),
"PPLG": ("seat of government of a political entity", ""),
- "PPLH": (
- "historical populated place",
- "a populated place that no longer exists"),
+ "PPLH": ("historical populated place", "a populated place that no longer exists"),
"PPLL": (
"populated locality",
- "an area similar to a locality but with a small group of dwellings or other buildings"),
+ "an area similar to a locality but with a small group of dwellings or other buildings",
+ ),
"PPLQ": ("abandoned populated place", ""),
"PPLR": (
"religious populated place",
- "a populated place whose population is largely engaged in religious occupations"),
+ "a populated place whose population is largely engaged in religious occupations",
+ ),
"PPLS": (
"populated places",
- "cities, towns, villages, or other agglomerations of buildings where people live and work"),
+ "cities, towns, villages, or other agglomerations of buildings where people live and work",
+ ),
"PPLW": (
"destroyed populated place",
- "a village, town or city destroyed by a natural disaster, or by war"),
+ "a village, town or city destroyed by a natural disaster, or by war",
+ ),
"PPLX": ("section of populated place", ""),
"STLMT": ("israeli settlement", ""),
- "RGN": ("region", "an area distinguished by one or more observable physical or cultural characteristics")}
+ "RGN": (
+ "region",
+ "an area distinguished by one or more observable physical or cultural characteristics",
+ ),
+}
class StbGeoQuerySettings:
-
- def __init__(self, kind='place'):
+ def __init__(self, kind="place"):
self.kind = kind
- self.score = u'http://stanbol.apache.org/ontology/entityhub/query#score'
- self.uri = 'id'
- self.label = u'http://www.w3.org/2000/01/rdf-schema#label'
+ self.score = "http://stanbol.apache.org/ontology/entityhub/query#score"
+ self.uri = "id"
+ self.label = "http://www.w3.org/2000/01/rdf-schema#label"
self.kind = kind
self.last_selected = 0
- if kind == 'place':
- self.selected = [gn+'name', gn+'parentPCLI', gn+'parentCountry',
- gn+'parentADM1', gn+'parentADM2', gn+'parentADM3',
- gn+'population', gn+'featureCode', wgs84_pos+'lat',
- wgs84_pos+'long', gn+'alternateName', gn+'officialName',
- gn+'shortName', gn+'countryCode', gn+'parentFeature']
- self.stored_feature = {
- 'feature': gn+'PPLC',
- 'URL': URL_geonames % 'PPLC'
- }
- self.features = [{
- 'feature': gn+'PPLC',
- 'URL': URL_geonames % 'PPLC'
- },
- {
- 'feature': gn+'PPLA',
- 'URL': URL_geonames % 'PPLA'
- },
- {
- 'feature': gn+'PPLA2',
- 'URL': URL_geonames % 'PPLA2'
- },
- {
- 'feature': gn+'PPLA3',
- 'URL': URL_geonames % 'PPLA3'
- },
- {
- 'feature': gn+'PPLA4',
- 'URL': URL_geonames % 'PPLA4'
- },
- {
- 'feature': gn+'PPL',
- 'URL': URL_geonames % 'PPL'
- }]
- elif kind == 'admin':
- self.selected = [gn+'featureCode']
- self.stored_feature = {
- 'feature': gn+'PCLI',
- 'URL': URL_geonames % 'PCLI'
- }
- self.features = [{
- 'feature': gn+'PCLI',
- 'URL': URL_geonames % 'PCLI'
- },
- {
- 'feature': gn+'ADM1',
- 'URL': URL_geonames % 'ADM1'
- },
- {
- 'feature': gn+'ADM2',
- 'URL': URL_geonames % 'ADM2'
- },
- {
- 'feature': gn+'ADM3',
- 'URL': URL_geonames % 'ADM3'
- }
+ if kind == "place":
+ self.selected = [
+ gn + "name",
+ gn + "parentPCLI",
+ gn + "parentCountry",
+ gn + "parentADM1",
+ gn + "parentADM2",
+ gn + "parentADM3",
+ gn + "population",
+ gn + "featureCode",
+ wgs84_pos + "lat",
+ wgs84_pos + "long",
+ gn + "alternateName",
+ gn + "officialName",
+ gn + "shortName",
+ gn + "countryCode",
+ gn + "parentFeature",
+ ]
+ self.stored_feature = {"feature": gn + "PPLC", "URL": URL_geonames % "PPLC"}
+ self.features = [
+ {"feature": gn + "PPLC", "URL": URL_geonames % "PPLC"},
+ {"feature": gn + "PPLA", "URL": URL_geonames % "PPLA"},
+ {"feature": gn + "PPLA2", "URL": URL_geonames % "PPLA2"},
+ {"feature": gn + "PPLA3", "URL": URL_geonames % "PPLA3"},
+ {"feature": gn + "PPLA4", "URL": URL_geonames % "PPLA4"},
+ {"feature": gn + "PPL", "URL": URL_geonames % "PPL"},
+ ]
+ elif kind == "admin":
+ self.selected = [gn + "featureCode"]
+ self.stored_feature = {"feature": gn + "PCLI", "URL": URL_geonames % "PCLI"}
+ self.features = [
+ {"feature": gn + "PCLI", "URL": URL_geonames % "PCLI"},
+ {"feature": gn + "ADM1", "URL": URL_geonames % "ADM1"},
+ {"feature": gn + "ADM2", "URL": URL_geonames % "ADM2"},
+ {"feature": gn + "ADM3", "URL": URL_geonames % "ADM3"},
]
def get_next_feature(self, ft=False):
- if self.last_selected > len(self.features)-1:
+ if self.last_selected > len(self.features) - 1:
self.stored_feature = False
return False
if not ft:
- ft = self.features[self.last_selected]['feature']
+ ft = self.features[self.last_selected]["feature"]
for idnx, x in enumerate(self.features):
- if x['feature'] == ft:
+ if x["feature"] == ft:
try:
- self.last_selected = idnx+1
- self.stored_feature = self.features[idnx+1]
- return self.features[idnx+1]
+ self.last_selected = idnx + 1
+ self.stored_feature = self.features[idnx + 1]
+ return self.features[idnx + 1]
except:
return None
return self.features[0]
def get_data(self, query, adm=False):
- if self.kind == 'place' and adm:
+ if self.kind == "place" and adm:
data = {
- 'limit': 20, 'constraints': [{
- 'type': 'text',
- 'field': 'http://www.w3.org/2000/01/rdf-schema#label',
- 'text': query},
- {'type': 'reference', 'field': adm[1], 'value': adm[0]}
- ],
- 'selected': self.selected
+ "limit": 20,
+ "constraints": [
+ {
+ "type": "text",
+ "field": "http://www.w3.org/2000/01/rdf-schema#label",
+ "text": query,
+ },
+ {"type": "reference", "field": adm[1], "value": adm[0]},
+ ],
+ "selected": self.selected,
}
else:
data = {
- 'limit': 20, 'constraints': [{
- 'type': 'text',
- 'field': 'http://www.w3.org/2000/01/rdf-schema#label',
- 'text': query},
- ],
- 'selected': self.selected}
+ "limit": 20,
+ "constraints": [
+ {
+ "type": "text",
+ "field": "http://www.w3.org/2000/01/rdf-schema#label",
+ "text": query,
+ },
+ ],
+ "selected": self.selected,
+ }
return data
diff --git a/apis_core/default_settings/RDF_settings.py b/apis_core/default_settings/RDF_settings.py
index 70599b4..10e0360 100644
--- a/apis_core/default_settings/RDF_settings.py
+++ b/apis_core/default_settings/RDF_settings.py
@@ -1,417 +1,542 @@
-gno = 'http://www.geonames.org/ontology#'
+gno = "http://www.geonames.org/ontology#"
wgs84 = "http://www.w3.org/2003/01/geo/wgs84_pos#"
-gndo = 'http://d-nb.info/standards/elementset/gnd#'
+gndo = "http://d-nb.info/standards/elementset/gnd#"
owl = "http://www.w3.org/2002/07/owl#"
geo = "http://www.opengis.net/ont/geosparql#"
sett_RDF_generic = {
- 'Place': {
- 'data': [
+ "Place": {
+ "data": [
{
- 'base_url': 'http://sws.geonames.org/',
- 'url_appendix': 'about.rdf',
- 'kind': (
- (gno + 'featureCode', None),
- ),
- 'attributes': [
+ "base_url": "http://sws.geonames.org/",
+ "url_appendix": "about.rdf",
+ "kind": ((gno + "featureCode", None),),
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gno + 'officialName', ('language', 'de')),),
- (('objects', 'prefName', gno + 'officialName', ('language', 'en')),),
- (('objects', 'prefName', gno + 'name', None),),
- (('objects', 'prefName', gno + 'alternateName', ('language', 'de')),),
- (('objects', 'prefName', gno + 'alternateName', ('language', 'en')),)
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gno + "officialName",
+ ("language", "de"),
+ ),
+ ),
+ (
+ (
+ "objects",
+ "prefName",
+ gno + "officialName",
+ ("language", "en"),
+ ),
+ ),
+ (("objects", "prefName", gno + "name", None),),
+ (
+ (
+ "objects",
+ "prefName",
+ gno + "alternateName",
+ ("language", "de"),
+ ),
+ ),
+ (
+ (
+ "objects",
+ "prefName",
+ gno + "alternateName",
+ ("language", "en"),
+ ),
+ ),
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
- (('objects', 'label', gno + 'alternateName', ('language', 'de')),),
- (('objects', 'label', gno + 'alternateName', ('language', 'en')),)
- )
+ "name": "label",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "label",
+ gno + "alternateName",
+ ("language", "de"),
+ ),
+ ),
+ (
+ (
+ "objects",
+ "label",
+ gno + "alternateName",
+ ("language", "en"),
+ ),
+ ),
+ ),
},
{
- 'name': 'lat',
- 'identifiers': (
- (('objects', 'lat', wgs84 + 'lat', None),),
- )
+ "name": "lat",
+ "identifiers": ((("objects", "lat", wgs84 + "lat", None),),),
},
{
- 'name': 'long',
- 'identifiers': (
- (('objects', 'lng', wgs84 + 'long', None),),
- )
+ "name": "long",
+ "identifiers": ((("objects", "lng", wgs84 + "long", None),),),
},
{
- 'name': 'parentFeature',
- 'identifiers': (
- (('objects', 'parentFeature', gno + 'parentFeature', None),),
- )
+ "name": "parentFeature",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "parentFeature",
+ gno + "parentFeature",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'parentCountry',
- 'identifiers': (
- (('objects', 'parentCountry', gno + 'parentCountry', None),),
- )
+ "name": "parentCountry",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "parentCountry",
+ gno + "parentCountry",
+ None,
+ ),
+ ),
+ ),
},
- ]
+ ],
},
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gndo + 'preferredNameForThePlaceOrGeographicName', None),),
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "preferredNameForThePlaceOrGeographicName",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
+ "name": "label",
+ "identifiers": (
(
- ('objects', 'label', gndo + 'variantNameForThePlaceOrGeographicName', None),
+ (
+ "objects",
+ "label",
+ gndo + "variantNameForThePlaceOrGeographicName",
+ None,
+ ),
),
),
},
{
- 'name': 'latlong',
- 'identifiers': (
- (('objects', 'latlong_base', geo + 'hasGeometry', None), '>',
- ('objects', 'latlong_geonode', geo + 'asWKT', None)
- ),
- )
+ "name": "latlong",
+ "identifiers": (
+ (
+ ("objects", "latlong_base", geo + "hasGeometry", None),
+ ">",
+ ("objects", "latlong_geonode", geo + "asWKT", None),
+ ),
+ ),
},
- ]
- }
+ ],
+ },
],
- 'matching': {
- 'attributes': {
- 'name': (
- (('prefName', None),),
- ),
- 'lat': (
- (('lat', None),),
- (('latlong_geonode', ('Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)', 2)),)
- ),
- 'lng': (
- (('lng', None),),
- (('latlong_geonode', ('Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)', 1)),)
+ "matching": {
+ "attributes": {
+ "name": ((("prefName", None),),),
+ "lat": (
+ (("lat", None),),
+ (
+ (
+ "latlong_geonode",
+ ("Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)", 2),
+ ),
+ ),
),
- },
- 'labels': {
- 'alternative name': (
- ('label', None),
+ "lng": (
+ (("lng", None),),
+ (
+ (
+ "latlong_geonode",
+ ("Point \( [+-]([0-9\.]+) [+-]([0-9\.]+)", 1),
+ ),
+ ),
),
- },
- 'linked objects':
- [
- {
- 'type': 'Place',
- 'kind': 'located in',
- 'object': (
- ('parentFeature', None),
- )
},
- {
- 'type': 'Place',
- 'kind': 'located in',
- 'object': (
- ('parentCountry', None),
- )
+ "labels": {
+ "alternative name": (("label", None),),
},
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "located in",
+ "object": (("parentFeature", None),),
+ },
+ {
+ "type": "Place",
+ "kind": "located in",
+ "object": (("parentCountry", None),),
+ },
],
- }
+ },
},
- 'Person': {
- 'data': [
+ "Person": {
+ "data": [
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
+ "name": "name",
+ "identifiers": (
(
- ('objects', 'prefNameNode', gndo + 'preferredNameEntityForThePerson', None),'>',
- ('objects', 'forename', gndo + 'forename', None), '=',
- ('objects', 'surname', gndo + 'surname', None)
- ),
+ (
+ "objects",
+ "prefNameNode",
+ gndo + "preferredNameEntityForThePerson",
+ None,
+ ),
+ ">",
+ ("objects", "forename", gndo + "forename", None),
+ "=",
+ ("objects", "surname", gndo + "surname", None),
+ ),
(
- ('objects', 'prefNameNode', gndo + 'preferredNameEntityForThePerson', None), '>',
- ('objects', 'descriptionNode', gndo + 'Description', None), '>',
- ('objects', 'personalNameAddition', gndo + 'nameAddition', None), '=',
- ('objects', 'personalNameCounting', gndo + 'counting', None), '=',
- ('objects', 'personalName', gndo + 'personalName', None),
+ (
+ "objects",
+ "prefNameNode",
+ gndo + "preferredNameEntityForThePerson",
+ None,
+ ),
+ ">",
+ (
+ "objects",
+ "descriptionNode",
+ gndo + "Description",
+ None,
+ ),
+ ">",
+ (
+ "objects",
+ "personalNameAddition",
+ gndo + "nameAddition",
+ None,
+ ),
+ "=",
+ (
+ "objects",
+ "personalNameCounting",
+ gndo + "counting",
+ None,
+ ),
+ "=",
+ (
+ "objects",
+ "personalName",
+ gndo + "personalName",
+ None,
+ ),
),
-
- )
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
+ "name": "label",
+ "identifiers": (
(
-
- ('objects', 'label', gndo + 'variantNameForThePerson', None),
-
+ (
+ "objects",
+ "label",
+ gndo + "variantNameForThePerson",
+ None,
+ ),
),
),
},
{
- 'name': 'place of birth',
- 'identifiers': (
- (
- ('objects', 'place of birth', gndo + 'placeOfBirth', None),
+ "name": "place of birth",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "place of birth",
+ gndo + "placeOfBirth",
+ None,
+ ),
+ ),
),
- ),
},
{
- 'name': 'place of death',
- 'identifiers': (
- (
- ('objects', 'place of death', gndo + 'placeOfDeath', None),
+ "name": "place of death",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "place of death",
+ gndo + "placeOfDeath",
+ None,
+ ),
+ ),
),
- ),
},
{
- 'name': 'date of birth',
- 'identifiers': (
- (
- ('objects', 'date of birth', gndo + 'dateOfBirth', None),
+ "name": "date of birth",
+ "identifiers": (
+ (("objects", "date of birth", gndo + "dateOfBirth", None),),
),
- ),
},
{
- 'name': 'date of death',
- 'identifiers': (
- (
- ('objects', 'date of death', gndo + 'dateOfDeath', None),
+ "name": "date of death",
+ "identifiers": (
+ (("objects", "date of death", gndo + "dateOfDeath", None),),
),
- ),
},
- ]
+ ],
},
{
- 'base_url': 'https://www.wikidata.org/wiki/Special:EntityData/',
- 'url_appendix': '.rdf',
- 'attributes': [
- {
- 'name': 'name',
- 'identifiers': (
- (
- ('objects', '')
- )
- )
- },
- ]
- }
- ],
- 'matching': {
- 'attributes': {
- 'name': (
- (('surname', None),
- ),
- (('personalNameAddition', None),
- )
- ),
- 'first_name': (
- (('forename', None),),
- (('personalName', None),
- ' ',
- ('personalNameCounting', None)
- ),
- ),
- 'start_date_written': (
- (('date of birth', None),),
- ),
- 'end_date_written': (
- (('date of death', None),),
- ),
+ "base_url": "https://www.wikidata.org/wiki/Special:EntityData/",
+ "url_appendix": ".rdf",
+ "attributes": [
+ {"name": "name", "identifiers": ((("objects", "")))},
+ ],
},
- 'labels': {
- 'alternative name': (
- ('label', None),
+ ],
+ "matching": {
+ "attributes": {
+ "name": ((("surname", None),), (("personalNameAddition", None),)),
+ "first_name": (
+ (("forename", None),),
+ (("personalName", None), " ", ("personalNameCounting", None)),
),
+ "start_date_written": ((("date of birth", None),),),
+ "end_date_written": ((("date of death", None),),),
},
- 'linked objects':
- [
- {
- 'type': 'Place',
- 'kind': 'born in',
- 'object': (
- ('place of birth', None),
- )
- },
- {
- 'type': 'Place',
- 'kind': 'died in',
- 'object': (
- ('place of death', None),
- )
+ "labels": {
+ "alternative name": (("label", None),),
},
- ]
- }
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "born in",
+ "object": (("place of birth", None),),
+ },
+ {
+ "type": "Place",
+ "kind": "died in",
+ "object": (("place of death", None),),
+ },
+ ],
+ },
},
- 'Event': {
- 'data': [
+ "Event": {
+ "data": [
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gndo + 'preferredNameForTheSubjectHeading', None),),
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "preferredNameForTheSubjectHeading",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'start',
- 'identifiers': (
- (('objects', 'start_date', gndo + 'dateOfEstablishment', None),),
- )
+ "name": "start",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "start_date",
+ gndo + "dateOfEstablishment",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'end',
- 'identifiers': (
- (('objects', 'end_date', gndo + 'dateOfTermination', None),),
- )
+ "name": "end",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "end_date",
+ gndo + "dateOfTermination",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
- (('objects', 'label', gndo + 'variantNameForTheSubjectHeading', None),),
- )
+ "name": "label",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "label",
+ gndo + "variantNameForTheSubjectHeading",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'place of event',
- 'identifiers': (
- (('objects', 'place of event', gndo + 'place', None),),
- )
- }
+ "name": "place of event",
+ "identifiers": (
+ (("objects", "place of event", gndo + "place", None),),
+ ),
+ },
],
}
],
- 'matching': {
- 'attributes': {
- 'name': (
- (('prefName', None),),
- ),
- 'start_date_written': (
- (('start_date', None),),
- ),
- 'end_date_written': (
- (('end_date', None),),
- )
- },
- 'labels': {
- 'alternative name': (
- ('label', None),
- )
- },
- 'linked objects': [
- {
- 'type': 'Place',
- 'kind': 'place of event',
- 'object': (
- ('place of event', None),
- )
+ "matching": {
+ "attributes": {
+ "name": ((("prefName", None),),),
+ "start_date_written": ((("start_date", None),),),
+ "end_date_written": ((("end_date", None),),),
},
+ "labels": {"alternative name": (("label", None),)},
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "place of event",
+ "object": (("place of event", None),),
+ },
],
- }
+ },
},
- 'Institution': {
- 'data': [
+ "Institution": {
+ "data": [
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gndo + 'preferredNameForTheCorporateBody', None),),
- (('objects', 'prefName', gndo + 'variantNameForTheCorporateBody', None),),
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "preferredNameForTheCorporateBody",
+ None,
+ ),
+ ),
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "variantNameForTheCorporateBody",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'alternativeName',
- 'identifiers': (
- (('objects', 'alternativeName', gndo + 'variantNameForTheCorporateBody', None),),
- )
+ "name": "alternativeName",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "alternativeName",
+ gndo + "variantNameForTheCorporateBody",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'start',
- 'identifiers': (
- (('objects', 'start', gndo + 'dateOfEstablishment', None),),
- )
+ "name": "start",
+ "identifiers": (
+ (("objects", "start", gndo + "dateOfEstablishment", None),),
+ ),
},
{
- 'name': 'end',
- 'identifiers': (
- (('objects', 'end', gndo + 'dateOfTermination', None),),
- )
+ "name": "end",
+ "identifiers": (
+ (("objects", "end", gndo + "dateOfTermination", None),),
+ ),
},
{
- 'name': 'placeOfBusiness',
- 'identifiers': (
- (('objects', 'placeOfBusiness', gndo + 'placeOfBusiness', None),),
- )
+ "name": "placeOfBusiness",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "placeOfBusiness",
+ gndo + "placeOfBusiness",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'succeeding',
- 'identifiers': (
- (('objects', 'succeeding', gndo + 'succeedingCorporateBody', None),),
- )
+ "name": "succeeding",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "succeeding",
+ gndo + "succeedingCorporateBody",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'preceding',
- 'identifiers': (
- (('objects', 'preceding', gndo + 'precedingCorporateBody', None),),
- )
- }
- ]
+ "name": "preceding",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "preceding",
+ gndo + "precedingCorporateBody",
+ None,
+ ),
+ ),
+ ),
+ },
+ ],
}
],
- 'matching': {
- 'attributes': {
- 'name': (
- (('prefName', None),),
- ),
- 'start_date_written': (
- (('start', None),),
- ),
- 'end_date_written': (
- (('end', None),),
- )
+ "matching": {
+ "attributes": {
+ "name": ((("prefName", None),),),
+ "start_date_written": ((("start", None),),),
+ "end_date_written": ((("end", None),),),
},
- 'labels': {
- 'alternative name': (
- ('alternativeName', None),
- )
- },
- 'linked objects': [
- {
- 'type': 'Place',
- 'kind': 'located in',
- 'object': (
- ('placeOfBusiness', None),
- )
- },
- {
- 'type': 'Institution',
- 'kind': 'preceding',
- 'object': (
- ('preceding', None),
- )
- },
- {
- 'type': 'Institution',
- 'kind': 'succeeding',
- 'object': (
- ('succeeding', None),
- )
- },
- ]
- }
- }
+ "labels": {"alternative name": (("alternativeName", None),)},
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "located in",
+ "object": (("placeOfBusiness", None),),
+ },
+ {
+ "type": "Institution",
+ "kind": "preceding",
+ "object": (("preceding", None),),
+ },
+ {
+ "type": "Institution",
+ "kind": "succeeding",
+ "object": (("succeeding", None),),
+ },
+ ],
+ },
+ },
}
diff --git a/apis_core/default_settings/RDF_settings_new.py b/apis_core/default_settings/RDF_settings_new.py
index fa0334d..8652752 100644
--- a/apis_core/default_settings/RDF_settings_new.py
+++ b/apis_core/default_settings/RDF_settings_new.py
@@ -1,23 +1,20 @@
-gno = 'http://www.geonames.org/ontology#'
+gno = "http://www.geonames.org/ontology#"
wgs84 = "http://www.w3.org/2003/01/geo/wgs84_pos#"
-gndo = 'http://d-nb.info/standards/elementset/gnd#'
+gndo = "http://d-nb.info/standards/elementset/gnd#"
owl = "http://www.w3.org/2002/07/owl#"
geo = "http://www.opengis.net/ont/geosparql#"
-sameAs = [
- "http://schema.org/sameAs",
- "http://www.w3.org/2002/07/owl#sameAs"
-]
+sameAs = ["http://schema.org/sameAs", "http://www.w3.org/2002/07/owl#sameAs"]
sett_RDF_generic = {
- 'Place': {
- 'data': [
+ "Place": {
+ "data": [
{
- 'base_url': 'http://sws.geonames.org/',
- 'attributes': [
+ "base_url": "http://sws.geonames.org/",
+ "attributes": [
{
- 'name': 'name',
- 'sparql': """
+ "name": "name",
+ "sparql": """
PREFIX gn:
SELECT ?prefName (LANG(?prefName) AS ?lang)
WHERE {{
@@ -27,8 +24,8 @@
""",
},
{
- 'name': 'altName',
- 'sparql': """
+ "name": "altName",
+ "sparql": """
PREFIX gn:
SELECT ?altName (LANG(?altName) AS ?lang)
WHERE {{
@@ -38,8 +35,8 @@
""",
},
{
- 'name': 'kind',
- 'sparql': """
+ "name": "kind",
+ "sparql": """
PREFIX gn:
SELECT ?kind
WHERE {{
@@ -47,8 +44,9 @@
}}
""",
},
- {'name': 'lat-long',
- 'sparql': """
+ {
+ "name": "lat-long",
+ "sparql": """
PREFIX gn:
PREFIX wgs84_pos:
SELECT ?lat ?long
@@ -57,365 +55,427 @@
wgs84_pos:long ?long
}}
""",
-
},
- {'name': 'parent',
- 'sparql': """
+ {
+ "name": "parent",
+ "sparql": """
PREFIX gn:
SELECT ?parent
WHERE {{
<{subject}> gn:parentCountry ?parent
}}
""",
-
- },
- ]
+ },
+ ],
},
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gndo + 'preferredNameForThePlaceOrGeographicName', None),),
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "preferredNameForThePlaceOrGeographicName",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
+ "name": "label",
+ "identifiers": (
(
- ('objects', 'label', gndo + 'variantNameForThePlaceOrGeographicName', None),
+ (
+ "objects",
+ "label",
+ gndo + "variantNameForThePlaceOrGeographicName",
+ None,
+ ),
),
),
},
{
- 'name': 'latlong',
- 'identifiers': (
- (('objects', 'latlong_base', geo + 'hasGeometry', None), '>',
- ('objects', 'latlong_geonode', geo + 'asWKT', None)
- ),
- )
+ "name": "latlong",
+ "identifiers": (
+ (
+ ("objects", "latlong_base", geo + "hasGeometry", None),
+ ">",
+ ("objects", "latlong_geonode", geo + "asWKT", None),
+ ),
+ ),
},
- ]
- }
+ ],
+ },
],
- 'matching': {
- 'attributes': {
- 'name': {
- 'string': '{prefName}',
- 'regex': None
- },
- 'kind': [{
- 'string': '{kind}',
- 'accessor': 'name',
- 'regex': None
- },],
- 'lat': {
- 'identifier': 'lat-long',
- 'string': '{lat}'
- },
- 'lng': {
- 'identifier': 'lat-long',
- 'string': '{long}'
- }
+ "matching": {
+ "attributes": {
+ "name": {"string": "{prefName}", "regex": None},
+ "kind": [
+ {"string": "{kind}", "accessor": "name", "regex": None},
+ ],
+ "lat": {"identifier": "lat-long", "string": "{lat}"},
+ "lng": {"identifier": "lat-long", "string": "{long}"},
},
- 'labels': {
- 'alternative name': (
- ('label', None),
- ),
- },
- 'linked objects':
- [
- {
- 'type': 'Place',
- 'kind': 'located in',
- 'object': 'parent'
+ "labels": {
+ "alternative name": (("label", None),),
},
+ "linked objects": [
+ {"type": "Place", "kind": "located in", "object": "parent"},
],
- }
+ },
},
- 'Person': {
- 'data': [
+ "Person": {
+ "data": [
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
+ "name": "name",
+ "identifiers": (
(
- ('objects', 'prefNameNode', gndo + 'preferredNameEntityForThePerson', None),'>',
- ('objects', 'forename', gndo + 'forename', None), '=',
- ('objects', 'surname', gndo + 'surname', None)
- ),
+ (
+ "objects",
+ "prefNameNode",
+ gndo + "preferredNameEntityForThePerson",
+ None,
+ ),
+ ">",
+ ("objects", "forename", gndo + "forename", None),
+ "=",
+ ("objects", "surname", gndo + "surname", None),
+ ),
(
- ('objects', 'prefNameNode', gndo + 'preferredNameEntityForThePerson', None), '>',
- ('objects', 'descriptionNode', gndo + 'Description', None), '>',
- ('objects', 'personalNameAddition', gndo + 'nameAddition', None), '=',
- ('objects', 'personalNameCounting', gndo + 'counting', None), '=',
- ('objects', 'personalName', gndo + 'personalName', None),
+ (
+ "objects",
+ "prefNameNode",
+ gndo + "preferredNameEntityForThePerson",
+ None,
+ ),
+ ">",
+ (
+ "objects",
+ "descriptionNode",
+ gndo + "Description",
+ None,
+ ),
+ ">",
+ (
+ "objects",
+ "personalNameAddition",
+ gndo + "nameAddition",
+ None,
+ ),
+ "=",
+ (
+ "objects",
+ "personalNameCounting",
+ gndo + "counting",
+ None,
+ ),
+ "=",
+ (
+ "objects",
+ "personalName",
+ gndo + "personalName",
+ None,
+ ),
),
-
- )
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
+ "name": "label",
+ "identifiers": (
(
-
- ('objects', 'label', gndo + 'variantNameForThePerson', None),
-
+ (
+ "objects",
+ "label",
+ gndo + "variantNameForThePerson",
+ None,
+ ),
),
),
},
{
- 'name': 'place of birth',
- 'identifiers': (
- (
- ('objects', 'place of birth', gndo + 'placeOfBirth', None),
+ "name": "place of birth",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "place of birth",
+ gndo + "placeOfBirth",
+ None,
+ ),
+ ),
),
- ),
},
{
- 'name': 'place of death',
- 'identifiers': (
- (
- ('objects', 'place of death', gndo + 'placeOfDeath', None),
+ "name": "place of death",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "place of death",
+ gndo + "placeOfDeath",
+ None,
+ ),
+ ),
),
- ),
},
{
- 'name': 'date of birth',
- 'identifiers': (
- (
- ('objects', 'date of birth', gndo + 'dateOfBirth', None),
+ "name": "date of birth",
+ "identifiers": (
+ (("objects", "date of birth", gndo + "dateOfBirth", None),),
),
- ),
},
{
- 'name': 'date of death',
- 'identifiers': (
- (
- ('objects', 'date of death', gndo + 'dateOfDeath', None),
+ "name": "date of death",
+ "identifiers": (
+ (("objects", "date of death", gndo + "dateOfDeath", None),),
),
- ),
},
- ]
+ ],
},
{
- 'base_url': 'https://www.wikidata.org/wiki/Special:EntityData/',
- 'url_appendix': '.rdf',
- 'attributes': [
- {
- 'name': 'name',
- 'identifiers': (
- (
- ('objects', '')
- )
- )
- },
- ]
- }
- ],
- 'matching': {
- 'attributes': {
- 'name': "{self}",
- 'first_name': (
- (('forename', None),),
- (('personalName', None),
- ' ',
- ('personalNameCounting', None)
- ),
- ),
- 'start_date_written': (
- (('date of birth', None),),
- ),
- 'end_date_written': (
- (('date of death', None),),
- ),
+ "base_url": "https://www.wikidata.org/wiki/Special:EntityData/",
+ "url_appendix": ".rdf",
+ "attributes": [
+ {"name": "name", "identifiers": ((("objects", "")))},
+ ],
},
- 'labels': {
- 'alternative name': (
- ('label', None),
+ ],
+ "matching": {
+ "attributes": {
+ "name": "{self}",
+ "first_name": (
+ (("forename", None),),
+ (("personalName", None), " ", ("personalNameCounting", None)),
),
+ "start_date_written": ((("date of birth", None),),),
+ "end_date_written": ((("date of death", None),),),
},
- 'linked objects':
- [
- {
- 'type': 'Place',
- 'kind': 'born in',
- 'object': (
- ('place of birth', None),
- )
- },
- {
- 'type': 'Place',
- 'kind': 'died in',
- 'object': (
- ('place of death', None),
- )
+ "labels": {
+ "alternative name": (("label", None),),
},
- ]
- }
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "born in",
+ "object": (("place of birth", None),),
+ },
+ {
+ "type": "Place",
+ "kind": "died in",
+ "object": (("place of death", None),),
+ },
+ ],
+ },
},
- 'Event': {
- 'data': [
+ "Event": {
+ "data": [
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gndo + 'preferredNameForTheSubjectHeading', None),),
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "preferredNameForTheSubjectHeading",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'start',
- 'identifiers': (
- (('objects', 'start_date', gndo + 'dateOfEstablishment', None),),
- )
+ "name": "start",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "start_date",
+ gndo + "dateOfEstablishment",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'end',
- 'identifiers': (
- (('objects', 'end_date', gndo + 'dateOfTermination', None),),
- )
+ "name": "end",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "end_date",
+ gndo + "dateOfTermination",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'label',
- 'identifiers': (
- (('objects', 'label', gndo + 'variantNameForTheSubjectHeading', None),),
- )
+ "name": "label",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "label",
+ gndo + "variantNameForTheSubjectHeading",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'place of event',
- 'identifiers': (
- (('objects', 'place of event', gndo + 'place', None),),
- )
- }
+ "name": "place of event",
+ "identifiers": (
+ (("objects", "place of event", gndo + "place", None),),
+ ),
+ },
],
}
],
- 'matching': {
- 'attributes': {
- 'name': (
- (('prefName', None),),
- ),
- 'start_date_written': (
- (('start_date', None),),
- ),
- 'end_date_written': (
- (('end_date', None),),
- )
- },
- 'labels': {
- 'alternative name': (
- ('label', None),
- )
- },
- 'linked objects': [
- {
- 'type': 'Place',
- 'kind': 'place of event',
- 'object': (
- ('place of event', None),
- )
+ "matching": {
+ "attributes": {
+ "name": ((("prefName", None),),),
+ "start_date_written": ((("start_date", None),),),
+ "end_date_written": ((("end_date", None),),),
},
+ "labels": {"alternative name": (("label", None),)},
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "place of event",
+ "object": (("place of event", None),),
+ },
],
- }
+ },
},
- 'Institution': {
- 'data': [
+ "Institution": {
+ "data": [
{
- 'base_url': 'http://d-nb.info/gnd/',
- 'url_appendix': 'about/rdf',
- 'attributes': [
+ "base_url": "http://d-nb.info/gnd/",
+ "url_appendix": "about/rdf",
+ "attributes": [
{
- 'name': 'name',
- 'identifiers': (
- (('objects', 'prefName', gndo + 'preferredNameForTheCorporateBody', None),),
- (('objects', 'prefName', gndo + 'variantNameForTheCorporateBody', None),),
- )
+ "name": "name",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "preferredNameForTheCorporateBody",
+ None,
+ ),
+ ),
+ (
+ (
+ "objects",
+ "prefName",
+ gndo + "variantNameForTheCorporateBody",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'alternativeName',
- 'identifiers': (
- (('objects', 'alternativeName', gndo + 'variantNameForTheCorporateBody', None),),
- )
+ "name": "alternativeName",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "alternativeName",
+ gndo + "variantNameForTheCorporateBody",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'start',
- 'identifiers': (
- (('objects', 'start', gndo + 'dateOfEstablishment', None),),
- )
+ "name": "start",
+ "identifiers": (
+ (("objects", "start", gndo + "dateOfEstablishment", None),),
+ ),
},
{
- 'name': 'end',
- 'identifiers': (
- (('objects', 'end', gndo + 'dateOfTermination', None),),
- )
+ "name": "end",
+ "identifiers": (
+ (("objects", "end", gndo + "dateOfTermination", None),),
+ ),
},
{
- 'name': 'placeOfBusiness',
- 'identifiers': (
- (('objects', 'placeOfBusiness', gndo + 'placeOfBusiness', None),),
- )
+ "name": "placeOfBusiness",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "placeOfBusiness",
+ gndo + "placeOfBusiness",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'succeeding',
- 'identifiers': (
- (('objects', 'succeeding', gndo + 'succeedingCorporateBody', None),),
- )
+ "name": "succeeding",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "succeeding",
+ gndo + "succeedingCorporateBody",
+ None,
+ ),
+ ),
+ ),
},
{
- 'name': 'preceding',
- 'identifiers': (
- (('objects', 'preceding', gndo + 'precedingCorporateBody', None),),
- )
- }
- ]
+ "name": "preceding",
+ "identifiers": (
+ (
+ (
+ "objects",
+ "preceding",
+ gndo + "precedingCorporateBody",
+ None,
+ ),
+ ),
+ ),
+ },
+ ],
}
],
- 'matching': {
- 'attributes': {
- 'name': "{prefName}",
- 'start_date_written': (
- (('start', None),),
- ),
- 'end_date_written': (
- (('end', None),),
- )
+ "matching": {
+ "attributes": {
+ "name": "{prefName}",
+ "start_date_written": ((("start", None),),),
+ "end_date_written": ((("end", None),),),
},
- 'labels': {
- 'alternative name': (
- ('alternativeName', None),
- )
- },
- 'linked objects': [
- {
- 'type': 'Place',
- 'kind': 'located in',
- 'object': (
- ('placeOfBusiness', None),
- )
- },
- {
- 'type': 'Institution',
- 'kind': 'preceding',
- 'object': (
- ('preceding', None),
- )
- },
- {
- 'type': 'Institution',
- 'kind': 'succeeding',
- 'object': (
- ('succeeding', None),
- )
- },
- ]
- }
- }
-}
\ No newline at end of file
+ "labels": {"alternative name": (("alternativeName", None),)},
+ "linked objects": [
+ {
+ "type": "Place",
+ "kind": "located in",
+ "object": (("placeOfBusiness", None),),
+ },
+ {
+ "type": "Institution",
+ "kind": "preceding",
+ "object": (("preceding", None),),
+ },
+ {
+ "type": "Institution",
+ "kind": "succeeding",
+ "object": (("succeeding", None),),
+ },
+ ],
+ },
+ },
+}
diff --git a/apis_core/helper_functions/ContentType.py b/apis_core/helper_functions/ContentType.py
index d885568..a65fdde 100644
--- a/apis_core/helper_functions/ContentType.py
+++ b/apis_core/helper_functions/ContentType.py
@@ -6,20 +6,18 @@
class GetContentTypes:
-
# class memeber dictionary, used for caching ContentType objects in method get_content_type_of_class_or_instance
class_content_type_dict = {}
-
def get_names(self):
"""Function to create Module/Class name tuples
Returns:
[list]: [list of Modile/Class tuples]
- """
+ """
res = []
for cls in self._lst_cont:
- res.append((cls.__module__.split('.')[-2], cls.__name__))
+ res.append((cls.__module__.split(".")[-2], cls.__name__))
return res
def get_model_classes(self):
@@ -27,10 +25,9 @@ def get_model_classes(self):
Returns:
[list]: [django model classes]
- """
+ """
return self._lst_cont
-
@classmethod
def get_content_type_of_class_or_instance(cls, model_class_or_instance):
"""
@@ -55,18 +52,29 @@ def get_content_type_of_class_or_instance(cls, model_class_or_instance):
)
if model_class not in cls.class_content_type_dict:
- cls.class_content_type_dict[model_class] = ContentType.objects.get(model=model_class.__name__)
+ cls.class_content_type_dict[model_class] = ContentType.objects.get(
+ model=model_class.__name__
+ )
return cls.class_content_type_dict[model_class]
-
def __init__(self, lst_conts=None):
"""
Args:
lst_conts ([list], optional): [list of entity names]. Defaults to list of apis_core entities.
- """
- models_exclude = ["texttype_collections", "relationbaseclass", "baserelationmanager", "relationpublishedqueryset"]
- apis_modules = ['apis_core.apis_metainfo.models', 'apis_core.apis_vocabularies.models', 'apis_core.apis_entities.models', 'apis_core.apis_relations.models']
+ """
+ models_exclude = [
+ "texttype_collections",
+ "relationbaseclass",
+ "baserelationmanager",
+ "relationpublishedqueryset",
+ ]
+ apis_modules = [
+ "apis_core.apis_metainfo.models",
+ "apis_core.apis_vocabularies.models",
+ "apis_core.apis_entities.models",
+ "apis_core.apis_relations.models",
+ ]
if lst_conts is not None:
r2 = []
for c in lst_conts:
@@ -78,7 +86,14 @@ def __init__(self, lst_conts=None):
lst_cont = []
for m in lst_cont_pre:
for cls_n in dir(m):
- if not cls_n.startswith('__') and "__module__" in list(dir(getattr(m, cls_n))):
- if getattr(m, cls_n).__module__ in apis_modules and cls_n.lower() not in models_exclude and not "abstract" in cls_n.lower() and inspect.isclass(getattr(m, cls_n)):
+ if not cls_n.startswith("__") and "__module__" in list(
+ dir(getattr(m, cls_n))
+ ):
+ if (
+ getattr(m, cls_n).__module__ in apis_modules
+ and cls_n.lower() not in models_exclude
+ and not "abstract" in cls_n.lower()
+ and inspect.isclass(getattr(m, cls_n))
+ ):
lst_cont.append(getattr(m, cls_n))
- self._lst_cont = lst_cont
\ No newline at end of file
+ self._lst_cont = lst_cont
diff --git a/apis_core/helper_functions/DateParser.py b/apis_core/helper_functions/DateParser.py
index dfc46ba..fb59c9d 100644
--- a/apis_core/helper_functions/DateParser.py
+++ b/apis_core/helper_functions/DateParser.py
@@ -3,7 +3,7 @@
from datetime import datetime, timedelta
-def parse_date( date_string: str ) -> (datetime, datetime, datetime):
+def parse_date(date_string: str) -> (datetime, datetime, datetime):
"""
function to parse a string date field of an entity
@@ -20,7 +20,6 @@ def parse_date( date_string: str ) -> (datetime, datetime, datetime):
ending date of a range if user passed a range value either implicit or explicit.
"""
-
def parse_date_range_individual(date, ab=False, bis=False):
"""
As a sub function to parse_date, this function parse_date_individual handles a very single date since
@@ -47,7 +46,6 @@ def parse_date_range_individual(date, ab=False, bis=False):
if a single date was given.
"""
-
def get_last_day_of_month(month, year):
"""
Helper function to return the last day of a given month and year (respecting leap years)
@@ -88,10 +86,10 @@ def get_last_day_of_month(month, year):
# no valid month
raise ValueError("Month " + str(month) + " does not exist.")
-
-
# replace all kinds of delimiters
- date = date.replace(" ", "").replace("-", ".").replace("/", ".").replace("\\", ".")
+ date = (
+ date.replace(" ", "").replace("-", ".").replace("/", ".").replace("\\", ".")
+ )
# parse into variables for use later
year = None
@@ -132,7 +130,6 @@ def get_last_day_of_month(month, year):
# No sensical interpretation found
raise ValueError("Could not interpret date.")
-
if (ab and bis) or year is None:
# both ab and bis in one single date are not valid, neither is the absence of a year.
raise ValueError("Could not interpret date.")
@@ -157,11 +154,10 @@ def get_last_day_of_month(month, year):
day_ab = day
day_bis = day
-
# return a tuple from a single date (which the calling function has to further process)
return (
datetime(year=year, month=month_ab, day=day_ab),
- datetime(year=year, month=month_bis, day=day_bis)
+ datetime(year=year, month=month_bis, day=day_bis),
)
else:
@@ -188,7 +184,6 @@ def get_last_day_of_month(month, year):
return datetime(year=year, month=month, day=day)
-
try:
# return variables
@@ -199,14 +194,17 @@ def get_last_day_of_month(month, year):
# split for angle brackets, check if explicit iso date is contained within them
date_split_angle = re.split(r"(<.*?>)", date_string)
-
if len(date_split_angle) > 1:
# date string contains angle brackets. Parse them, ignore the rest
def parse_iso_date(date_string):
date_string_split = date_string.split("-")
try:
- return datetime(year=int(date_string_split[0]), month=int(date_string_split[1]), day=int(date_string_split[2]) )
+ return datetime(
+ year=int(date_string_split[0]),
+ month=int(date_string_split[1]),
+ day=int(date_string_split[2]),
+ )
except:
raise ValueError("Invalid iso date: ", date_string)
@@ -226,7 +224,8 @@ def parse_iso_date(date_string):
if len(dates_iso) != 1 and len(dates_iso) != 3:
# only either one iso date or three are allowed
raise ValueError(
- "Incorrect number of dates given. Within angle brackets only one or three (separated by commas) are allowed.")
+ "Incorrect number of dates given. Within angle brackets only one or three (separated by commas) are allowed."
+ )
elif len(dates_iso) == 3:
# three iso dates indicate further start and end dates
@@ -246,7 +245,6 @@ def parse_iso_date(date_string):
if date_single_string != "":
date_single = parse_iso_date(date_single_string)
-
else:
# date string contains no angle brackets. Interpret the possible date formats
date_string = date_string.lower()
@@ -270,7 +268,9 @@ def parse_iso_date(date_string):
found_ab = True
# parse the next value which must be a parsable date string
- date_ab = parse_date_range_individual(date_split_ab_bis[i + 1], ab=True)
+ date_ab = parse_date_range_individual(
+ date_split_ab_bis[i + 1], ab=True
+ )
elif v == "bis":
# indicates that the next value must be an end date
@@ -281,7 +281,9 @@ def parse_iso_date(date_string):
found_bis = True
# parse the next value which must be a parsable date string
- date_bis = parse_date_range_individual(date_split_ab_bis[i + 1], bis=True)
+ date_bis = parse_date_range_individual(
+ date_split_ab_bis[i + 1], bis=True
+ )
elif v != "" and not found_ab and not found_bis and not found_single:
# indicates that this value must be a date
@@ -305,7 +307,9 @@ def parse_iso_date(date_string):
# calculate difference between start and end date of range,
# and use it to calculate a single date for usage as median.
- days_delta_half = math.floor((date_bis - date_ab).days / 2, )
+ days_delta_half = math.floor(
+ (date_bis - date_ab).days / 2,
+ )
date_single = date_ab + timedelta(days=days_delta_half)
elif date_ab is not None and date_bis is None:
@@ -324,8 +328,9 @@ def parse_iso_date(date_string):
return date_single, date_ab, date_bis
-
-def get_date_help_text_from_dates(single_date, single_start_date, single_end_date, single_date_written):
+def get_date_help_text_from_dates(
+ single_date, single_start_date, single_end_date, single_date_written
+):
"""
function for creating string help text from parsed dates, to provide feedback to the user
about the parsing status of a given date field.
@@ -346,7 +351,6 @@ def get_date_help_text_from_dates(single_date, single_start_date, single_end_dat
The text to be displayed underneath a date field, informing the user about the parsing result
"""
-
# check which of the dates could be parsed to construct the relevant feedback text
help_text = ""
@@ -361,10 +365,14 @@ def get_date_help_text_from_dates(single_date, single_start_date, single_end_dat
if single_start_date:
# date has start range
- help_text += \
- str(single_start_date.year) + "-" + \
- str(single_start_date.month) + "-" + \
- str(single_start_date.day) + " until "
+ help_text += (
+ str(single_start_date.year)
+ + "-"
+ + str(single_start_date.month)
+ + "-"
+ + str(single_start_date.day)
+ + " until "
+ )
else:
# date has no start range, then write "undefined"
@@ -374,10 +382,13 @@ def get_date_help_text_from_dates(single_date, single_start_date, single_end_dat
if single_end_date:
# date has end range
- help_text += \
- str(single_end_date.year) + "-" + \
- str(single_end_date.month) + "-" + \
- str(single_end_date.day)
+ help_text += (
+ str(single_end_date.year)
+ + "-"
+ + str(single_end_date.month)
+ + "-"
+ + str(single_end_date.day)
+ )
else:
# date has no start range, then write "undefined"
@@ -387,15 +398,20 @@ def get_date_help_text_from_dates(single_date, single_start_date, single_end_dat
else:
# date has no start nor end range. Use single date then.
- help_text += \
- str(single_date.year) + "-" + \
- str(single_date.month) + "-" + \
- str(single_date.day)
+ help_text += (
+ str(single_date.year)
+ + "-"
+ + str(single_date.month)
+ + "-"
+ + str(single_date.day)
+ )
elif single_date_written is not None:
# date input field is not empty but it could not be parsed either. Show parsing info and help text
- help_text = "Date could not be interpreted " + get_date_help_text_default()
+ help_text = (
+ "Date could not be interpreted " + get_date_help_text_default()
+ )
else:
# date field is completely empty. Show help text only
@@ -405,7 +421,6 @@ def get_date_help_text_from_dates(single_date, single_start_date, single_end_dat
return help_text
-
def get_date_help_text_default():
return "Dates are interpreted by defined rules. If this fails, an iso-date can be explicitly set with '<YYYY-MM-DD>'."
diff --git a/apis_core/helper_functions/EntityRelationFieldGenerator.py b/apis_core/helper_functions/EntityRelationFieldGenerator.py
index 961ca3e..03ec92f 100644
--- a/apis_core/helper_functions/EntityRelationFieldGenerator.py
+++ b/apis_core/helper_functions/EntityRelationFieldGenerator.py
@@ -1,5 +1,6 @@
from django.db import models
+
def generate_all_fields():
"""
This function goes through every entity, relation, and relationtype model and automatically wires them together
@@ -17,7 +18,7 @@ def generate_all_fields():
And each of those fields are ManyToMany Managers where their django methods can be used upon, such as all() and filter()
E.g. for PersonWork these fields are auto-generated: related_person, and related_work.
- for PersonPerson: related_personA, and related_personB
+ for PersonPerson: related_persona, and related_personb
:return: None
"""
@@ -27,8 +28,6 @@ def generate_all_fields():
from apis_core.apis_relations.models import AbstractRelation
from apis_core.apis_vocabularies.models import AbstractRelationType
-
-
def create_function_get_related_entity_class(related_entity_class):
"""
:param related_entity_class: the class which the generated class method shall return
@@ -43,9 +42,6 @@ def create_function_get_related_entity_field_name(related_entity_field_name):
"""
return classmethod(lambda cls: related_entity_field_name)
-
-
-
def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
"""
helper function to pair up the relation and relationtype classes so that potential mismatches between them are
@@ -80,22 +76,24 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
message = ""
for cls in no_pairing_found:
- message += "Found no corresponding Relation or RelationType class to: \n" + str(cls) + "!"
+ message += (
+ "Found no corresponding Relation or RelationType class to: \n"
+ + str(cls)
+ + "!"
+ )
raise Exception(message)
return rc_rtc_pairs
-
# all relation, relationtype classes to be iterated over:
relation_relationtype_pairs = pair_up_relations_relationtypes(
relation_classes=AbstractRelation.get_all_relation_classes(),
- relationtype_classes=AbstractRelationType.get_all_relationtype_classes()
+ relationtype_classes=AbstractRelationType.get_all_relationtype_classes(),
)
# all entity classes to be iterated over:
entity_classes = AbstractEntity.get_all_entity_classes()
-
# Iterate over all entity classes, twice, so that all relations between all entity classes are covered.
for entity_class_a in entity_classes:
for entity_class_b in entity_classes:
@@ -106,16 +104,16 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
# inner loop iterating over each of the relation_class and relationtype at the same time
for relation_class, relationtype_class in relation_relationtype_pairs:
-
# Check if current relation related to both entities
# Note that this way two entites are checked twice, such as person-place and place-person
# but however in the relation model only one of these two exists. Thus the right one will be picked.
- if entity_class_name_a + entity_class_name_b == relation_class.__name__.lower():
+ if (
+ entity_class_name_a + entity_class_name_b
+ == relation_class.__name__.lower()
+ ):
if entity_class_a != entity_class_b:
-
-
# On relation models: generate fields from relation to entity and from relation to relationtype
################################################################################################
@@ -125,7 +123,9 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
# To stick to common Django ORM Syntax, set the field name in the related entity class to
# the current relation name and add '_set' to it (since going from the entity one would have
# multiple relation instances possibly.)
- relation_field_name_in_other_class = entity_class_name_a + entity_class_name_b + "_set"
+ relation_field_name_in_other_class = (
+ entity_class_name_a + entity_class_name_b + "_set"
+ )
# Create the related entity field A.
models.ForeignKey(
@@ -133,7 +133,7 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
blank=True,
null=True,
on_delete=models.CASCADE,
- related_name=relation_field_name_in_other_class
+ related_name=relation_field_name_in_other_class,
).contribute_to_class(relation_class, relation_field_name_a)
# Create the related entity field B.
@@ -142,7 +142,7 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
blank=True,
null=True,
on_delete=models.CASCADE,
- related_name=relation_field_name_in_other_class
+ related_name=relation_field_name_in_other_class,
).contribute_to_class(relation_class, relation_field_name_b)
# Create the related relationtype field
@@ -151,7 +151,7 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
blank=True,
null=True,
on_delete=models.CASCADE,
- related_name=relation_field_name_in_other_class
+ related_name=relation_field_name_in_other_class,
).contribute_to_class(relation_class, "relation_type")
# Implemented the following methods programmatically by setting the respective relations,
@@ -159,42 +159,72 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
# Note that these methods are first defined as stumps within AbstractRelation for documentation
# purposes.
- relation_class.get_related_entity_classA = \
+ relation_class.get_related_entity_classa = (
create_function_get_related_entity_class(entity_class_a)
+ )
- relation_class.get_related_entity_classB = \
+ relation_class.get_related_entity_classb = (
create_function_get_related_entity_class(entity_class_b)
-
- relation_class.get_related_entity_field_nameA = \
- create_function_get_related_entity_field_name(relation_field_name_a)
-
- relation_class.get_related_entity_field_nameB = \
- create_function_get_related_entity_field_name(relation_field_name_b)
-
- relation_class.add_relation_class_of_entity_class(entity_class_a)
- relation_class.add_relation_class_of_entity_class(entity_class_b)
+ )
+
+ relation_class.get_related_entity_field_namea = (
+ create_function_get_related_entity_field_name(
+ relation_field_name_a
+ )
+ )
+
+ relation_class.get_related_entity_field_nameb = (
+ create_function_get_related_entity_field_name(
+ relation_field_name_b
+ )
+ )
+
+ relation_class.add_relation_class_of_entity_class(
+ entity_class_a
+ )
+ relation_class.add_relation_class_of_entity_class(
+ entity_class_b
+ )
relation_class.add_relation_field_name_of_entity_class(
- relation_name=relation_field_name_in_other_class, entity_class=entity_class_a)
+ relation_name=relation_field_name_in_other_class,
+ entity_class=entity_class_a,
+ )
relation_class.add_relation_field_name_of_entity_class(
- relation_name=relation_field_name_in_other_class, entity_class=entity_class_b)
-
-
+ relation_name=relation_field_name_in_other_class,
+ entity_class=entity_class_b,
+ )
# On entity models: generate fields from entity to entity and from entity to relationtype
################################################################################################
field_name_to_entity_a = entity_class_name_a + "_set"
field_name_to_entity_b = entity_class_name_b + "_set"
- field_name_to_entity_b_relationtype = entity_class_name_b + "_relationtype_set"
- field_name_to_entity_a_relationtype = entity_class_name_a + "_relationtype_set"
+ field_name_to_entity_b_relationtype = (
+ entity_class_name_b + "_relationtype_set"
+ )
+ field_name_to_entity_a_relationtype = (
+ entity_class_name_a + "_relationtype_set"
+ )
# Add those names already into the respective class's list of field names
- entity_class_a.add_related_entity_field_name(field_name_to_entity_b)
- entity_class_b.add_related_entity_field_name(field_name_to_entity_a)
- entity_class_a.add_related_relationtype_field_name(field_name_to_entity_b_relationtype)
- entity_class_b.add_related_relationtype_field_name(field_name_to_entity_a_relationtype)
- relationtype_class.add_related_entity_field_name(field_name_to_entity_b)
- relationtype_class.add_related_entity_field_name(field_name_to_entity_a)
+ entity_class_a.add_related_entity_field_name(
+ field_name_to_entity_b
+ )
+ entity_class_b.add_related_entity_field_name(
+ field_name_to_entity_a
+ )
+ entity_class_a.add_related_relationtype_field_name(
+ field_name_to_entity_b_relationtype
+ )
+ entity_class_b.add_related_relationtype_field_name(
+ field_name_to_entity_a_relationtype
+ )
+ relationtype_class.add_related_entity_field_name(
+ field_name_to_entity_b
+ )
+ relationtype_class.add_related_entity_field_name(
+ field_name_to_entity_a
+ )
# entity A to entity B, and B back to A
models.ManyToManyField(
@@ -210,7 +240,9 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
through=relation_class,
related_name=field_name_to_entity_a,
blank=True,
- ).contribute_to_class(entity_class_a, field_name_to_entity_b_relationtype)
+ ).contribute_to_class(
+ entity_class_a, field_name_to_entity_b_relationtype
+ )
# entity B to RelationType via entity A, and RelationType back to B
models.ManyToManyField(
@@ -218,14 +250,12 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
through=relation_class,
related_name=field_name_to_entity_b,
blank=True,
- ).contribute_to_class(entity_class_b, field_name_to_entity_a_relationtype)
-
-
+ ).contribute_to_class(
+ entity_class_b, field_name_to_entity_a_relationtype
+ )
else:
-
-
# On relation models: generate fields from relation to entity and from relation to relationtype
################################################################################################
@@ -233,13 +263,12 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
entity_class_name = entity_class_name_a
entity_class = entity_class_a
-
- relation_field_name_a = "related_" + entity_class_name + "A"
- relation_field_name_b = "related_" + entity_class_name + "B"
+ relation_field_name_a = "related_" + entity_class_name + "a"
+ relation_field_name_b = "related_" + entity_class_name + "b"
# Within APIS it was manually set that from a given entity which relates to a relation containing
# the same entity class twice (e.g. PersonPerson), within the given entity class the
- # field's name was 'related_A', and 'related_B' (e.g. Person.related_personA).
+ # field's name was 'related_A', and 'related_B' (e.g. Person.related_persona).
# This is not consistent with the other relation fields of a given entity
# (e.g. for PersonWork, in Person and Work, it would refer to the relation via 'personwork_set').
#
@@ -249,7 +278,9 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
# generated as before.
relation_field_name_in_other_class_a = relation_field_name_b
relation_field_name_in_other_class_b = relation_field_name_a
- relation_field_name_in_other_class = entity_class_name_a + entity_class_name_b + "_set"
+ relation_field_name_in_other_class = (
+ entity_class_name_a + entity_class_name_b + "_set"
+ )
# TODO __sresch__ : use the following related name for consistency reasons once most code breaking parts due to this change are identified.
#
@@ -259,8 +290,8 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
# to be a bit more consistent with other usages. So, uncomment the following once breaking parts
# are identified and prepared for it.
#
- # relation_field_name_from_entity_a = entity_class_name * 2 + "B_set"
- # relation_field_name_from_entity_b = entity_class_name * 2 + "A_set"
+ # relation_field_name_from_entity_a = entity_class_name * 2 + "b_set"
+ # relation_field_name_from_entity_b = entity_class_name * 2 + "a_set"
# Create the related entity field A.
models.ForeignKey(
@@ -268,7 +299,7 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
blank=True,
null=True,
on_delete=models.CASCADE,
- related_name=relation_field_name_in_other_class_a
+ related_name=relation_field_name_in_other_class_a,
).contribute_to_class(relation_class, relation_field_name_a)
# Create the related entity field B.
@@ -277,7 +308,7 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
blank=True,
null=True,
on_delete=models.CASCADE,
- related_name=relation_field_name_in_other_class_b
+ related_name=relation_field_name_in_other_class_b,
).contribute_to_class(relation_class, relation_field_name_b)
# Create the related relaiontype field
@@ -286,7 +317,7 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
blank=True,
null=True,
on_delete=models.CASCADE,
- related_name=relation_field_name_in_other_class
+ related_name=relation_field_name_in_other_class,
).contribute_to_class(relation_class, "relation_type")
# Implemented the following methods programmatically by setting the respective relations,
@@ -294,42 +325,68 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
# Note that these methods are first defined as stumps within AbstractRelation for documentation
# purposes.
- relation_class.get_related_entity_classA = \
+ relation_class.get_related_entity_classa = (
create_function_get_related_entity_class(entity_class)
+ )
- relation_class.get_related_entity_classB = \
+ relation_class.get_related_entity_classb = (
create_function_get_related_entity_class(entity_class)
+ )
- relation_class.get_related_entity_field_nameA = \
- create_function_get_related_entity_field_name(relation_field_name_a)
+ relation_class.get_related_entity_field_namea = (
+ create_function_get_related_entity_field_name(
+ relation_field_name_a
+ )
+ )
- relation_class.get_related_entity_field_nameB = \
- create_function_get_related_entity_field_name(relation_field_name_b)
+ relation_class.get_related_entity_field_nameb = (
+ create_function_get_related_entity_field_name(
+ relation_field_name_b
+ )
+ )
relation_class.add_relation_class_of_entity_class(entity_class)
relation_class.add_relation_field_name_of_entity_class(
- relation_name=relation_field_name_in_other_class_a, entity_class=entity_class)
+ relation_name=relation_field_name_in_other_class_a,
+ entity_class=entity_class,
+ )
relation_class.add_relation_field_name_of_entity_class(
- relation_name=relation_field_name_in_other_class_b, entity_class=entity_class)
-
-
+ relation_name=relation_field_name_in_other_class_b,
+ entity_class=entity_class,
+ )
# On entity models: generate fields from entity to entity and from entity to relationtype
################################################################################################
# Define all the names for the ManyToMany fields generated below
- field_name_to_entity_a = entity_class_name_a + "A_set"
- field_name_to_entity_b = entity_class_name_b + "B_set"
- field_name_to_entity_b_relationtype = entity_class_name_b + "B_relationtype_set"
- field_name_to_entity_a_relationtype = entity_class_name_a + "A_relationtype_set"
+ field_name_to_entity_a = entity_class_name_a + "a_set"
+ field_name_to_entity_b = entity_class_name_b + "b_set"
+ field_name_to_entity_b_relationtype = (
+ entity_class_name_b + "b_relationtype_set"
+ )
+ field_name_to_entity_a_relationtype = (
+ entity_class_name_a + "a_relationtype_set"
+ )
# Add those names already into the respective class's list of field names
- entity_class_a.add_related_entity_field_name(field_name_to_entity_b)
- entity_class_b.add_related_entity_field_name(field_name_to_entity_a)
- entity_class_a.add_related_relationtype_field_name(field_name_to_entity_b_relationtype)
- entity_class_b.add_related_relationtype_field_name(field_name_to_entity_a_relationtype)
- relationtype_class.add_related_entity_field_name(field_name_to_entity_b)
- relationtype_class.add_related_entity_field_name(field_name_to_entity_a)
+ entity_class_a.add_related_entity_field_name(
+ field_name_to_entity_b
+ )
+ entity_class_b.add_related_entity_field_name(
+ field_name_to_entity_a
+ )
+ entity_class_a.add_related_relationtype_field_name(
+ field_name_to_entity_b_relationtype
+ )
+ entity_class_b.add_related_relationtype_field_name(
+ field_name_to_entity_a_relationtype
+ )
+ relationtype_class.add_related_entity_field_name(
+ field_name_to_entity_b
+ )
+ relationtype_class.add_related_entity_field_name(
+ field_name_to_entity_a
+ )
# entity A to same entity B, and B back to A
models.ManyToManyField(
@@ -338,7 +395,10 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
related_name=field_name_to_entity_a,
blank=True,
symmetrical=False,
- through_fields=("related_" + entity_class_name_a + "A", "related_" + entity_class_name_b + "B")
+ through_fields=(
+ "related_" + entity_class_name_a + "a",
+ "related_" + entity_class_name_b + "b",
+ ),
).contribute_to_class(entity_class_a, field_name_to_entity_b)
# entity A to RelationType via entity B, and RelationType back to A
@@ -348,8 +408,13 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
related_name=field_name_to_entity_a,
blank=True,
symmetrical=False,
- through_fields=("related_" + entity_class_name_a + "A", "relation_type")
- ).contribute_to_class(entity_class_a, field_name_to_entity_b_relationtype)
+ through_fields=(
+ "related_" + entity_class_name_a + "a",
+ "relation_type",
+ ),
+ ).contribute_to_class(
+ entity_class_a, field_name_to_entity_b_relationtype
+ )
# entity B to RelationType via entity A, and RelationType back to B
models.ManyToManyField(
@@ -358,10 +423,13 @@ def pair_up_relations_relationtypes(relation_classes, relationtype_classes):
related_name=field_name_to_entity_a_relationtype,
blank=True,
symmetrical=False,
- through_fields=("relation_type", "related_" + entity_class_name_b + "B")
- ).contribute_to_class(relationtype_class, field_name_to_entity_b)
-
-
+ through_fields=(
+ "relation_type",
+ "related_" + entity_class_name_b + "b",
+ ),
+ ).contribute_to_class(
+ relationtype_class, field_name_to_entity_b
+ )
# if entity_class_a_name + entity_class_b_name == relation_class.__name__.lower()
# equals to True, then for entity_class_a and entity_class_b, their respective relation class
diff --git a/apis_core/helper_functions/RDFParser.py b/apis_core/helper_functions/RDFParser.py
index 1b55bd7..7ffef60 100644
--- a/apis_core/helper_functions/RDFParser.py
+++ b/apis_core/helper_functions/RDFParser.py
@@ -24,30 +24,33 @@
from apis_core.default_settings.RDF_settings_new import sameAs
APIS_RDF_YAML_SETTINGS = getattr(
- settings,
- 'APIS_RDF_YAML_SETTINGS',
- os.path.join(os.path.dirname(__file__), '../default_settings', 'RDF_default_settings.yml')
- )
+ settings,
+ "APIS_RDF_YAML_SETTINGS",
+ os.path.join(
+ os.path.dirname(__file__), "../default_settings", "RDF_default_settings.yml"
+ ),
+)
APIS_RDF_URI_SETTINGS = getattr(
- settings,
- 'APIS_RDF_URI_SETTINGS',
- os.path.join(os.path.dirname(__file__), '../default_settings', "URI_replace_settings.yml")
- )
+ settings,
+ "APIS_RDF_URI_SETTINGS",
+ os.path.join(
+ os.path.dirname(__file__), "../default_settings", "URI_replace_settings.yml"
+ ),
+)
def clean_uri(sett, uri):
- for dom in sett['mappings']:
- if dom['domain'] in uri:
- m = re.match(dom['regex'], uri)
+ for dom in sett["mappings"]:
+ if dom["domain"] in uri:
+ m = re.match(dom["regex"], uri)
if m:
- uri = dom['replace'].format(m.group(1))
+ uri = dom["replace"].format(m.group(1))
return uri
class PartialFormatter(string.Formatter):
-
- def __init__(self, missing='-', bad_fmt='!!'):
+ def __init__(self, missing="-", bad_fmt="!!"):
self.missing, self.bad_fmt = missing, bad_fmt
def get_field(self, field_name, args, kwargs):
@@ -78,7 +81,7 @@ class RDFParser(object):
@property
def _settings_complete(self):
- sett = yaml.load(open(self._rdf_settings_file, 'r'), Loader=yaml.FullLoader)
+ sett = yaml.load(open(self._rdf_settings_file, "r"), Loader=yaml.FullLoader)
return sett
@property
@@ -87,13 +90,13 @@ def _settings(self):
Reads settings file and saves it
:return: (dict) dict of settings file
"""
- sett = yaml.load(open(self._rdf_settings_file, 'r'), Loader=yaml.FullLoader)
- res = {'data': []}
- for v in sett[self.kind]['data']:
- if v['base_url'] in self.uri:
- res['data'] = v
- res['matching'] = sett[self.kind]['matching']
- res['sameAs'] = sameAs
+ sett = yaml.load(open(self._rdf_settings_file, "r"), Loader=yaml.FullLoader)
+ res = {"data": []}
+ for v in sett[self.kind]["data"]:
+ if v["base_url"] in self.uri:
+ res["data"] = v
+ res["matching"] = sett[self.kind]["matching"]
+ res["sameAs"] = sameAs
return res
@staticmethod
@@ -111,7 +114,9 @@ def _exist(self, uri, uri_check=True):
return True, self.objct.objects.get(uri__uri=uri)
else:
if uri in RDFParser._reserved_uris.keys() and uri_check:
- if (time.time() - RDFParser._reserved_uris[uri]) < (self._preserve_uri_minutes * 60):
+ if (time.time() - RDFParser._reserved_uris[uri]) < (
+ self._preserve_uri_minutes * 60
+ ):
raise ValueError("URI used by other instance")
else:
RDFParser._reserved_uris[uri] = time.time()
@@ -134,12 +139,12 @@ def _parse(self):
pref_fin = []
u = None
count = 0
- u = self._settings_complete[self.kind]['data'][count]['base_url']
+ u = self._settings_complete[self.kind]["data"][count]["base_url"]
while u:
if u not in self.uri:
lst_pref.append(u)
count += 1
- u = self._settings_complete[self.kind]['data'][count]['base_url']
+ u = self._settings_complete[self.kind]["data"][count]["base_url"]
else:
u = False
for o in g.objects(URIRef(self.uri), OWL.sameAs):
@@ -152,11 +157,13 @@ def _parse(self):
self.uri = pref_fin[0][1]
self._graph = g
res = dict()
- for s in self._settings['data']['attributes']:
- sp = s.get('sparql', False)
+ for s in self._settings["data"]["attributes"]:
+ sp = s.get("sparql", False)
if sp:
- sp2 = self._sparql_to_pandas(g.query(sp, initBindings={'subject': URIRef(self.uri)}))
- res[s.get('name', 'no identifier provided')] = pd.DataFrame(sp2)
+ sp2 = self._sparql_to_pandas(
+ g.query(sp, initBindings={"subject": URIRef(self.uri)})
+ )
+ res[s.get("name", "no identifier provided")] = pd.DataFrame(sp2)
self._attributes = res
return res
@@ -164,7 +171,7 @@ def _add_same_as(self):
"""
adds the same as links as defined in the settings to the entity
"""
- for sa in self._settings['sameAs']:
+ for sa in self._settings["sameAs"]:
for su in self._graph.objects((self._subject, URIRef(sa))):
Uri.objects.create(uri=su, entity=self.objct)
@@ -197,7 +204,7 @@ def save(self):
if exist.count() > 0:
if exist[0].entity is not None:
return exist[0].entity
- self.objct.status = 'distinct'
+ self.objct.status = "distinct"
for obj in self._foreign_keys:
try:
attr2, created = obj[1].objects.get_or_create(**obj[2])
@@ -205,7 +212,9 @@ def save(self):
except MultipleObjectsReturned:
pass
self.objct.save()
- def_coll, created = Collection.objects.get_or_create(name='Default import collection')
+ def_coll, created = Collection.objects.get_or_create(
+ name="Default import collection"
+ )
self.objct.collection.add(def_coll)
self.saved = True
self._objct_uri.entity = self.objct
@@ -214,7 +223,9 @@ def save(self):
lab_new = []
for lab in self.labels:
lt, created = LabelType.objects.get_or_create(name=lab[2])
- l1 = Label.objects.create(label=lab[0], label_type=lt, temp_entity=self.objct)
+ l1 = Label.objects.create(
+ label=lab[0], label_type=lt, temp_entity=self.objct
+ )
lab_new.append(l1)
self.labels = lab_new
rel_obj_new = []
@@ -226,19 +237,32 @@ def save(self):
pass
for obj in self.related_objcts:
for u3 in obj[1]:
- ent1 = RDFParser(u3, obj[2], uri_check=self._uri_check, preserve_uri_minutes=self._preserve_uri_minutes).get_or_create(depth=0)
+ ent1 = RDFParser(
+ u3,
+ obj[2],
+ uri_check=self._uri_check,
+ preserve_uri_minutes=self._preserve_uri_minutes,
+ ).get_or_create(depth=0)
if obj[2].lower() == self.kind.lower():
- mod = ContentType.objects.get(model=f"{self.kind.lower()*2}", app_label=self._app_label_relations).model_class()()
- setattr(mod, 'related_' + self.kind.lower() + 'A_id', self.objct.pk)
- setattr(mod, 'related_' + self.kind.lower() + 'B_id', ent1.pk)
+ mod = ContentType.objects.get(
+ model=f"{self.kind.lower()*2}",
+ app_label=self._app_label_relations,
+ ).model_class()()
+ setattr(mod, "related_" + self.kind.lower() + "A_id", self.objct.pk)
+ setattr(mod, "related_" + self.kind.lower() + "B_id", ent1.pk)
else:
- mod = ContentType.objects.filter(model__icontains=obj[2], app_label=self._app_label_relations).get(
- model__icontains=self.kind).model_class()()
- setattr(mod, 'related_' + self.kind.lower() + '_id', self.objct.pk)
- setattr(mod, 'related_' + obj[2].lower() + '_id', ent1.pk)
- voc = mod._meta.get_field('relation_type').related_model
+ mod = (
+ ContentType.objects.filter(
+ model__icontains=obj[2], app_label=self._app_label_relations
+ )
+ .get(model__icontains=self.kind)
+ .model_class()()
+ )
+ setattr(mod, "related_" + self.kind.lower() + "_id", self.objct.pk)
+ setattr(mod, "related_" + obj[2].lower() + "_id", ent1.pk)
+ voc = mod._meta.get_field("relation_type").related_model
voc1, created = voc.objects.get_or_create(name=obj[0])
- setattr(mod, 'relation_type_id', voc1.pk)
+ setattr(mod, "relation_type_id", voc1.pk)
mod.save()
rel_obj_new.append(mod)
self.related_objcts = rel_obj_new
@@ -264,11 +288,11 @@ def _prep_string(self, string, regex, linked=False, data_type=False):
:return: (str) converted string
"""
conv_mapping = {
- 'str': str,
- 'string': str,
- 'float': float,
- 'int': int,
- 'integer': int
+ "str": str,
+ "string": str,
+ "float": float,
+ "int": int,
+ "integer": int,
}
if string is None:
return None
@@ -280,12 +304,14 @@ def _prep_string(self, string, regex, linked=False, data_type=False):
else:
return None
if len(string) > 255:
- string = string[:250] + '...'
+ string = string[:250] + "..."
if linked:
g1 = rdflib.Graph()
g1.parse(string)
pref1 = (SKOS.prefLabel, RDFS.label)
- pref1 += tuple([URIRef(x) for x in self._settings['matching']['prefLabels']])
+ pref1 += tuple(
+ [URIRef(x) for x in self._settings["matching"]["prefLabels"]]
+ )
string = g1.preferredLabel(URIRef(string), labelProperties=pref1)
if len(string) > 0:
string = str(string[0][1])
@@ -303,30 +329,38 @@ def _normalize_uri(self, uri):
:param uri: (url) URI to normalize
:return: (url) converted URI
"""
- sett = yaml.load(open(self._uri_settings_file, 'r'), Loader=yaml.FullLoader)
+ sett = yaml.load(open(self._uri_settings_file, "r"), Loader=yaml.FullLoader)
return clean_uri(sett, uri)
- def merge(self, m_obj, app_label_relations='apis_relations'):
+ def merge(self, m_obj, app_label_relations="apis_relations"):
"""
:param m_obj: the object to merge into (must be an django model object instance)
:param app_label_relations: (string) the label of the Django app that contains the relations
:return: django object saved to db or False if nothing was saved
"""
- for rel in ContentType.objects.filter(app_label=app_label_relations, model__icontains=self.kind.lower()):
- rel_q = {'related_' + self.kind.lower(): m_obj}
+ for rel in ContentType.objects.filter(
+ app_label=app_label_relations, model__icontains=self.kind.lower()
+ ):
+ rel_q = {"related_" + self.kind.lower(): m_obj}
rel2 = rel.model_class()
try:
for rel_exst in rel2.objects.filter(**rel_q):
- setattr(rel_exst, 'related_'+self.kind.lower()+'_id', self.objct.pk)
+ setattr(
+ rel_exst, "related_" + self.kind.lower() + "_id", self.objct.pk
+ )
rel_exst.save()
except FieldError: # e.g. PlacePlace relations have different related_ fields
- rel_q = {'related_' + self.kind.lower()+'A': m_obj}
+ rel_q = {"related_" + self.kind.lower() + "A": m_obj}
for rel_exst in rel2.objects.filter(**rel_q):
- setattr(rel_exst, 'related_'+self.kind.lower()+'A_id', self.objct.pk)
+ setattr(
+ rel_exst, "related_" + self.kind.lower() + "A_id", self.objct.pk
+ )
rel_exst.save()
- rel_q = {'related_' + self.kind.lower() + 'B': m_obj}
+ rel_q = {"related_" + self.kind.lower() + "B": m_obj}
for rel_exst in rel2.objects.filter(**rel_q):
- setattr(rel_exst, 'related_'+self.kind.lower()+'B_id', self.objct.pk)
+ setattr(
+ rel_exst, "related_" + self.kind.lower() + "B_id", self.objct.pk
+ )
rel_exst.save()
for z in genUri.objects.filter(entity=m_obj):
z.entity_id = self.objct.pk
@@ -334,16 +368,22 @@ def merge(self, m_obj, app_label_relations='apis_relations'):
for z in Label.objects.filter(temp_entity=m_obj):
z.temp_entity_id = self.objct.pk
z.save()
- if hasattr(m_obj, 'first_name'):
- legacy_name = '{}, {}'.format(m_obj.name, m_obj.first_name)
+ if hasattr(m_obj, "first_name"):
+ legacy_name = "{}, {}".format(m_obj.name, m_obj.first_name)
else:
legacy_name = m_obj.name
- lt, created = LabelType.objects.get_or_create(name='legacy name')
- Label.objects.create(temp_entity_id=self.objct.pk, label=legacy_name, label_type=lt)
+ lt, created = LabelType.objects.get_or_create(name="legacy name")
+ Label.objects.create(
+ temp_entity_id=self.objct.pk, label=legacy_name, label_type=lt
+ )
for col in m_obj.collection.all():
self.objct.collection.add(col)
- if 'apis_highlighter' in settings.INSTALLED_APPS:
- for ann in m_obj.annotation_set.all(): # Todo: check if this works now with highlighter
+ if "apis_highlighter" in settings.INSTALLED_APPS:
+ for (
+ ann
+ ) in (
+ m_obj.annotation_set.all()
+ ): # Todo: check if this works now with highlighter
ann.entity_link = self.objct
ann.save()
for txt in m_obj.text.all():
@@ -354,7 +394,6 @@ def merge(self, m_obj, app_label_relations='apis_relations'):
m_obj.delete()
return self.objct
-
def create_objct(self, depth=2):
"""
Uses parsed attributes to create an object that is not yet persisted to the db.
@@ -362,82 +401,140 @@ def create_objct(self, depth=2):
:param depth: (int) depth to follow
"""
c_dict = dict()
- for s in self._settings['matching']['attributes'].keys():
- if 'domain' in self._settings['matching']['attributes'][s].keys():
- if self._settings['matching']['attributes'][s]['domain'] not in self.uri:
+ for s in self._settings["matching"]["attributes"].keys():
+ if "domain" in self._settings["matching"]["attributes"][s].keys():
+ if (
+ self._settings["matching"]["attributes"][s]["domain"]
+ not in self.uri
+ ):
if self.print_info:
- print(f"continue: {s} / {self.uri} / {self._settings['matching']['attributes'][s]['domain']}")
+ print(
+ f"continue: {s} / {self.uri} / {self._settings['matching']['attributes'][s]['domain']}"
+ )
continue
- access = self._settings['matching']['attributes'][s].get('accessor', None)
- field_name = self._settings['matching']['attributes'][s].get('field name', s)
+ access = self._settings["matching"]["attributes"][s].get("accessor", None)
+ field_name = self._settings["matching"]["attributes"][s].get(
+ "field name", s
+ )
fields_1 = self.objct._meta.get_field(field_name)
- local_regex = self._settings['matching']['attributes'][s].get('regex', None)
- local_linked = self._settings['matching']['attributes'][s].get('linked', None)
- local_data_type = self._settings['matching']['attributes'][s].get('data type', False)
- id_1 = self._settings['matching']['attributes'][s].get('identifier', s).split('.')[0]
+ local_regex = self._settings["matching"]["attributes"][s].get("regex", None)
+ local_linked = self._settings["matching"]["attributes"][s].get(
+ "linked", None
+ )
+ local_data_type = self._settings["matching"]["attributes"][s].get(
+ "data type", False
+ )
+ id_1 = (
+ self._settings["matching"]["attributes"][s]
+ .get("identifier", s)
+ .split(".")[0]
+ )
if isinstance(fields_1, TCharField) or isinstance(fields_1, TFloatField):
data = dict()
if id_1 in self._attributes.keys():
df = self._attributes[id_1]
- cols = [x for x in df.columns if x != 'lang']
+ cols = [x for x in df.columns if x != "lang"]
for c in cols:
data[c] = df.at[0, c]
if self.print_info:
print(f"data: {data}")
- if 'string' in self._settings['matching']['attributes'][s].keys():
- local_string = fmt.format(self._settings['matching']['attributes'][s]['string'], **data)
+ if "string" in self._settings["matching"]["attributes"][s].keys():
+ local_string = fmt.format(
+ self._settings["matching"]["attributes"][s]["string"],
+ **data,
+ )
else:
- local_string = fmt.format("{"+self._settings['matching']['attributes'][s]['identifier'].split('.')[-1]+"}", **data)
- c_dict[field_name] = self._prep_string(local_string, local_regex, local_linked, local_data_type)
+ local_string = fmt.format(
+ "{"
+ + self._settings["matching"]["attributes"][s][
+ "identifier"
+ ].split(".")[-1]
+ + "}",
+ **data,
+ )
+ c_dict[field_name] = self._prep_string(
+ local_string, local_regex, local_linked, local_data_type
+ )
elif isinstance(fields_1, TForeignKey):
data = dict()
c_dict_f = dict()
if id_1 in self._attributes.keys():
df = self._attributes[id_1]
- cols = [x for x in df.columns if x != 'lang']
+ cols = [x for x in df.columns if x != "lang"]
for c in cols:
data[c] = df.at[0, c]
- local_string = fmt.format(self._settings['matching']['attributes'][s]['string'], **data)
- c_dict_f[access] = self._prep_string(local_string, local_regex, local_linked, local_data_type)
- self._foreign_keys.append((field_name, self.objct._meta.get_field(s).related_model, c_dict_f))
+ local_string = fmt.format(
+ self._settings["matching"]["attributes"][s]["string"], **data
+ )
+ c_dict_f[access] = self._prep_string(
+ local_string, local_regex, local_linked, local_data_type
+ )
+ self._foreign_keys.append(
+ (field_name, self.objct._meta.get_field(s).related_model, c_dict_f)
+ )
elif isinstance(fields_1, TManyToMany):
df = self._attributes[id_1]
for idx, row in df.iterrows():
data = dict()
if id_1 in self._attributes.keys():
- cols = [x for x in df.columns if x != 'lang']
+ cols = [x for x in df.columns if x != "lang"]
for c in cols:
data[c] = row[c]
c_dict_f = dict()
- local_string = fmt.format(self._settings['matching']['attributes'][s]['string'], **data)
- c_dict_f[access] = self._prep_string(local_string, local_regex, local_linked, local_data_type)
- self._m2m.append((field_name, self.objct._meta.get_field(s).related_model, c_dict_f))
- if 'labels' in self._settings['matching'].keys():
- for lab in self._settings['matching']['labels']:
- at1 = lab['identifier'].split('.')
+ local_string = fmt.format(
+ self._settings["matching"]["attributes"][s]["string"],
+ **data,
+ )
+ c_dict_f[access] = self._prep_string(
+ local_string, local_regex, local_linked, local_data_type
+ )
+ self._m2m.append(
+ (
+ field_name,
+ self.objct._meta.get_field(s).related_model,
+ c_dict_f,
+ )
+ )
+ if "labels" in self._settings["matching"].keys():
+ for lab in self._settings["matching"]["labels"]:
+ at1 = lab["identifier"].split(".")
if at1[0] in self._attributes.keys():
if at1[-1] not in self._attributes[at1[0]].columns:
if self.print_info:
- print('label_missing')
+ print("label_missing")
continue
- if 'lang' not in self._attributes[at1[0]]:
- self._attributes[at1[0]]['lang'] = 'deu'
- u2 = self._attributes[at1[0]][[at1[-1], 'lang']]
+ if "lang" not in self._attributes[at1[0]]:
+ self._attributes[at1[0]]["lang"] = "deu"
+ u2 = self._attributes[at1[0]][[at1[-1], "lang"]]
for idx, row in u2.iterrows():
- self.labels.append((row[at1[-1]], row['lang'], lab['label type']))
+ self.labels.append(
+ (row[at1[-1]], row["lang"], lab["label type"])
+ )
- if depth > 0 and 'linked objects' in self._settings['matching'].keys():
- for v in self._settings['matching']['linked objects']:
- at1 = v['identifier'].split('.')
+ if depth > 0 and "linked objects" in self._settings["matching"].keys():
+ for v in self._settings["matching"]["linked objects"]:
+ at1 = v["identifier"].split(".")
if at1[0] in self._attributes.keys():
if at1[-1] in self._attributes[at1[0]].columns:
u2 = self._attributes[at1[0]][at1[-1]].tolist()
- self.related_objcts.append((v['kind'], u2, v['type']))
+ self.related_objcts.append((v["kind"], u2, v["type"]))
self.objct = self.objct(**c_dict)
- def __init__(self, uri, kind, app_label_entities="apis_entities", app_label_relations="apis_relations",
- app_label_vocabularies="apis_vocabularies", rdf_settings=APIS_RDF_YAML_SETTINGS,
- uri_settings=APIS_RDF_URI_SETTINGS, preserve_uri_minutes=5, use_preferred=False, uri_check=True, print_info=False, **kwargs):
+ def __init__(
+ self,
+ uri,
+ kind,
+ app_label_entities="apis_entities",
+ app_label_relations="apis_relations",
+ app_label_vocabularies="apis_vocabularies",
+ rdf_settings=APIS_RDF_YAML_SETTINGS,
+ uri_settings=APIS_RDF_URI_SETTINGS,
+ preserve_uri_minutes=5,
+ use_preferred=False,
+ uri_check=True,
+ print_info=False,
+ **kwargs,
+ ):
"""
:param uri: (url) Uri to parse the object from (http://test.at). The uri must start with a base url mentioned in the RDF parser settings file.
:param kind: (string) Kind of entity (Person, Place, Institution, Work, Event)
@@ -453,7 +550,9 @@ def __init__(self, uri, kind, app_label_entities="apis_entities", app_label_rela
self._preserve_uri_minutes = preserve_uri_minutes
self._uri_check = uri_check
self._use_preferred = use_preferred
- self.objct = ContentType.objects.get(app_label=app_label_entities, model__iexact=kind).model_class()
+ self.objct = ContentType.objects.get(
+ app_label=app_label_entities, model__iexact=kind
+ ).model_class()
self._app_label_relations = app_label_relations
self.kind = kind
self._foreign_keys = []
@@ -462,7 +561,7 @@ def __init__(self, uri, kind, app_label_entities="apis_entities", app_label_rela
self._objct_uri = Uri(uri=self.uri)
self._subject = URIRef(self.uri)
self.related_objcts = []
- force = kwargs.get('force', None)
+ force = kwargs.get("force", None)
self.labels = []
self.print_info = print_info
self.related_objcts = []
@@ -473,8 +572,7 @@ def __init__(self, uri, kind, app_label_entities="apis_entities", app_label_rela
self.objct = test[1]
self.created = False
if print_info:
- print('not created')
+ print("not created")
else:
self.created = True
o = self._parse()
-
diff --git a/apis_core/helper_functions/dl_models.py b/apis_core/helper_functions/dl_models.py
index 8388341..6e5c213 100644
--- a/apis_core/helper_functions/dl_models.py
+++ b/apis_core/helper_functions/dl_models.py
@@ -19,7 +19,12 @@
def extract_verbs_from_entity(
- ent, lst_orth, lst_orth_dict, accept_pos=['VERB', 'AUX', 'NOUN', 'ADP', 'PART'], add=True):
+ ent,
+ lst_orth,
+ lst_orth_dict,
+ accept_pos=["VERB", "AUX", "NOUN", "ADP", "PART"],
+ add=True,
+):
res = []
for y in ent:
head = y
@@ -48,28 +53,37 @@ def extract_verbs_from_entity(
def test_model(model, sent):
K.clear_session()
- script_dir = os.path.dirname(os.path.realpath('__file__'))
- fileh = open(os.path.join(script_dir,
- 'data/nlp_models/{}_vocab.obj'.format(model)), 'rb')
- lst_orth, lst_orth_dict, lst_labels, lst_labels_dict, lst_zero_label, lst_labels_dhae2 = pickle.load(fileh)
- model = load_model(os.path.join(script_dir,
- 'data/nlp_models/{}.h5'.format(model)))
+ script_dir = os.path.dirname(os.path.realpath("__file__"))
+ fileh = open(
+ os.path.join(script_dir, "data/nlp_models/{}_vocab.obj".format(model)), "rb"
+ )
+ (
+ lst_orth,
+ lst_orth_dict,
+ lst_labels,
+ lst_labels_dict,
+ lst_zero_label,
+ lst_labels_dhae2,
+ ) = pickle.load(fileh)
+ model = load_model(os.path.join(script_dir, "data/nlp_models/{}.h5".format(model)))
result = []
txt = nlp(sent)
tokens_lst = []
for ent in txt.ents:
print(ent)
- tokens, lemmas, pos_tags, shapes = extract_verbs_from_entity(ent, lst_orth, lst_orth_dict, add=False)
+ tokens, lemmas, pos_tags, shapes = extract_verbs_from_entity(
+ ent, lst_orth, lst_orth_dict, add=False
+ )
if len(tokens) > 0:
tokens_lst.append(tokens)
x_matrix2 = np.array(tokens_lst)
print(x_matrix2)
tokenizer = Tokenizer(num_words=len(lst_orth))
- x_matrix3 = tokenizer.sequences_to_matrix(tokens_lst, mode='binary')
+ x_matrix3 = tokenizer.sequences_to_matrix(tokens_lst, mode="binary")
zz = model.predict(x_matrix3, batch_size=32, verbose=1)
for idx1, z in enumerate(zz):
for idx, x in enumerate(zz[idx1]):
- v_id = '-'
+ v_id = "-"
for k in lst_labels_dict.keys():
if lst_labels_dict[k] == idx:
v_id = VocabsBaseClass.objects.get(id=k).name
diff --git a/apis_core/helper_functions/inter_annotator_agreement.py b/apis_core/helper_functions/inter_annotator_agreement.py
index 13d1560..5b53c11 100644
--- a/apis_core/helper_functions/inter_annotator_agreement.py
+++ b/apis_core/helper_functions/inter_annotator_agreement.py
@@ -6,7 +6,7 @@
from apis_core.apis_metainfo.models import Text, TempEntityClass
from apis_highlighter.models import Annotation
-if 'annotator agreement' in getattr(settings, "APIS_COMPONENTS", []):
+if "annotator agreement" in getattr(settings, "APIS_COMPONENTS", []):
from nltk.metrics import AnnotationTask
import pandas as pd
from sklearn.metrics import precision_recall_fscore_support
@@ -15,19 +15,21 @@
class InternalDataAgreement(object):
@staticmethod
- def internal_data_agreement_calc(texts, ann1, ann2, anno_proj=None, format_string='start_end_text'):
+ def internal_data_agreement_calc(
+ texts, ann1, ann2, anno_proj=None, format_string="start_end_text"
+ ):
if type(texts) == QuerySet:
- q = {'text__in': texts}
+ q = {"text__in": texts}
else:
- q = {'text': texts}
+ q = {"text": texts}
lst_user_ann = []
if anno_proj:
- q['annotation_project_id'] = anno_proj
+ q["annotation_project_id"] = anno_proj
lst_ann_fin = dict()
for v in [ann1, ann2]:
lst_ann = []
- q['user_added_id'] = v
- for an in Annotation.objects.filter(**q).order_by('start'):
+ q["user_added_id"] = v
+ for an in Annotation.objects.filter(**q).order_by("start"):
lst_ann.append(an.annotation_hash(format_string=format_string))
if an.user_added_id not in lst_user_ann:
lst_user_ann.append(an.user_added_id)
@@ -49,24 +51,34 @@ def internal_data_agreement_calc(texts, ann1, ann2, anno_proj=None, format_strin
else:
return AnnotationTask(data=ann_task)
- def precision_recall_calc(self, texts, gold_standard, user_group, anno_proj=None, format_string='start_end_text'):
+ def precision_recall_calc(
+ self,
+ texts,
+ gold_standard,
+ user_group,
+ anno_proj=None,
+ format_string="start_end_text",
+ ):
if type(texts) == QuerySet:
- q = {'text__in': texts}
+ q = {"text__in": texts}
else:
- q = {'text': texts}
+ q = {"text": texts}
if anno_proj:
- q['annotation_project_id'] = anno_proj
+ q["annotation_project_id"] = anno_proj
lst_ann_fin = dict()
if not format_string:
- format_string = 'start_end_text'
+ format_string = "start_end_text"
user_list = [gold_standard]
- user_list.extend(User.objects.filter(groups__pk=user_group).exclude(pk=gold_standard)
- .values_list('pk', flat=True))
+ user_list.extend(
+ User.objects.filter(groups__pk=user_group)
+ .exclude(pk=gold_standard)
+ .values_list("pk", flat=True)
+ )
df = pd.DataFrame()
for v in user_list:
lst_ann = []
- q['user_added_id'] = v
- for an in Annotation.objects.filter(**q).order_by('start'):
+ q["user_added_id"] = v
+ for an in Annotation.objects.filter(**q).order_by("start"):
lst_ann.append(an.annotation_hash(format_string=format_string))
lst_ann_fin[v] = lst_ann
gold_username = User.objects.get(pk=gold_standard).username
@@ -87,14 +99,15 @@ def precision_recall_calc(self, texts, gold_standard, user_group, anno_proj=None
if ann not in lst_ann_fin[u]:
gold_list.append(1)
ann_list.append(0)
- prec_res = precision_recall_fscore_support(np.array(gold_list), np.array(ann_list), average='binary',
- pos_label=1)
- for idx, k in enumerate(['precission', 'recall', 'fbeta_score', 'support']):
+ prec_res = precision_recall_fscore_support(
+ np.array(gold_list), np.array(ann_list), average="binary", pos_label=1
+ )
+ for idx, k in enumerate(["precission", "recall", "fbeta_score", "support"]):
df.loc[ann_username, k] = prec_res[idx]
return df
def get_html_table(self):
- css_class = 'table table-bordered table-hover'
+ css_class = "table table-bordered table-hover"
self.html_tables = dict()
self.html_tables_gold = None
if isinstance(self.texts, dict):
@@ -103,20 +116,36 @@ def get_html_table(self):
if self.texts_gold is not None:
self.html_tables_gold = dict()
for txt_id in self.texts_gold.keys():
- self.html_tables_gold[txt_id] = self.texts_gold[txt_id].to_html(classes=css_class)
+ self.html_tables_gold[txt_id] = self.texts_gold[txt_id].to_html(
+ classes=css_class
+ )
elif isinstance(self.texts, pd.DataFrame):
self.html_tables = self.texts.to_html(classes=css_class)
if self.texts_gold is not None:
self.html_tables_gold = self.texts_gold.to_html(classes=css_class)
return self.html_tables, self.html_tables_gold
- def __init__(self, texts, anno_proj, user_group, metrics='Do_alpha',
- format_string='start_end_text', combine=False, gold_standard=False):
+ def __init__(
+ self,
+ texts,
+ anno_proj,
+ user_group,
+ metrics="Do_alpha",
+ format_string="start_end_text",
+ combine=False,
+ gold_standard=False,
+ ):
if not type(texts) == QuerySet:
m_name = ContentType.objects.get_for_model(texts).name
- if m_name == 'person' or m_name == 'place' or m_name == 'institution' or m_name == 'event' or m_name == 'work':
+ if (
+ m_name == "person"
+ or m_name == "place"
+ or m_name == "institution"
+ or m_name == "event"
+ or m_name == "work"
+ ):
texts = Text.objects.filter(tempentityclass=texts).distinct()
- elif m_name == 'collection':
+ elif m_name == "collection":
t = TempEntityClass.objects.filter(collection=texts)
texts = Text.objects.filter(tempentityclass__in=t).distinct()
self.texts_gold = None
@@ -132,7 +161,7 @@ def __init__(self, texts, anno_proj, user_group, metrics='Do_alpha',
if not user_group:
user_qs = dict()
else:
- user_qs = {'groups__pk': user_group}
+ user_qs = {"groups__pk": user_group}
for txt in texts:
df = pd.DataFrame()
test = False
@@ -148,7 +177,10 @@ def __init__(self, texts, anno_proj, user_group, metrics='Do_alpha',
ann1.pk,
ann2.pk,
anno_proj=anno_proj,
- format_string=format_string),metrics)()
+ format_string=format_string,
+ ),
+ metrics,
+ )()
if pd.notnull(t):
test = True
except AttributeError as ex:
@@ -166,7 +198,9 @@ def __init__(self, texts, anno_proj, user_group, metrics='Do_alpha',
if gold_standard:
if combine:
self.texts_gold = self.precision_recall_calc(
- txt, gold_standard, user_group, anno_proj=anno_proj)
+ txt, gold_standard, user_group, anno_proj=anno_proj
+ )
else:
self.texts_gold[txt.pk] = self.precision_recall_calc(
- txt, gold_standard, user_group, anno_proj=anno_proj)
+ txt, gold_standard, user_group, anno_proj=anno_proj
+ )
diff --git a/apis_core/helper_functions/pylobid.py b/apis_core/helper_functions/pylobid.py
index 0f98636..07c6823 100644
--- a/apis_core/helper_functions/pylobid.py
+++ b/apis_core/helper_functions/pylobid.py
@@ -13,9 +13,11 @@ def create_qs(row, cell, q_field="dateOfBirth", char_limit=0):
return qs
-def lobid_qs(row, q_field='name', add_fields=[], base_url="https://lobid.org/gnd/search?q="):
- """ creates a lobid query string from the passed in fields"""
- search_url = base_url+row[q_field]+"&filter=type:Person"
+def lobid_qs(
+ row, q_field="name", add_fields=[], base_url="https://lobid.org/gnd/search?q="
+):
+ """creates a lobid query string from the passed in fields"""
+ search_url = base_url + row[q_field] + "&filter=type:Person"
if add_fields:
filters = []
for x in add_fields:
@@ -25,37 +27,31 @@ def lobid_qs(row, q_field='name', add_fields=[], base_url="https://lobid.org/gnd
return search_url
-def search_lobid(row, qs_field='query'):
- """ sends the value of the passed in field to lobid and returns the results in a dict """
+def search_lobid(row, qs_field="query"):
+ """sends the value of the passed in field to lobid and returns the results in a dict"""
query = row[qs_field]
- result = {
- 'query': query,
- 'status': 0,
- 'error': "",
- 'hits': 0,
- 'gnd': []
- }
+ result = {"query": query, "status": 0, "error": "", "hits": 0, "gnd": []}
r = requests.get(query)
try:
r = requests.get(query)
except requests.ConnectionError:
- result['error'] = "Connection Error"
+ result["error"] = "Connection Error"
return result
if r:
if r.status_code == 200:
- result['status'] = r.status_code
- result['hits'] = r.json()['totalItems']
- if result['hits'] == 0:
+ result["status"] = r.status_code
+ result["hits"] = r.json()["totalItems"]
+ if result["hits"] == 0:
gnd = []
- print('zero hits')
- elif result['hits'] == 1:
+ print("zero hits")
+ elif result["hits"] == 1:
print("one hit")
- result['gnd'] = [r.json()['member'][0]['gndIdentifier']]
+ result["gnd"] = [r.json()["member"][0]["gndIdentifier"]]
else:
- print("{} hits".format(result['hits']))
- result['gnd'] = [x['gndIdentifier'] for x in r.json()['member']]
+ print("{} hits".format(result["hits"]))
+ result["gnd"] = [x["gndIdentifier"] for x in r.json()["member"]]
else:
- result['status'] = r.status_code
+ result["status"] = r.status_code
return result
diff --git a/apis_core/helper_functions/stanbolQueries.py b/apis_core/helper_functions/stanbolQueries.py
index f03d45e..d77f2f5 100644
--- a/apis_core/helper_functions/stanbolQueries.py
+++ b/apis_core/helper_functions/stanbolQueries.py
@@ -2,7 +2,10 @@
import requests
-from apis_core.default_settings.NER_settings import StbGeoQuerySettings, autocomp_settings
+from apis_core.default_settings.NER_settings import (
+ StbGeoQuerySettings,
+ autocomp_settings,
+)
def decide_score_stanbol(results, dec_diff):
@@ -10,7 +13,10 @@ def decide_score_stanbol(results, dec_diff):
return results
if len(results) == 1:
return results[0]
- res2 = [(r['http://stanbol.apache.org/ontology/entityhub/query#score'][0]['value'], r) for r in results]
+ res2 = [
+ (r["http://stanbol.apache.org/ontology/entityhub/query#score"][0]["value"], r)
+ for r in results
+ ]
res2.sort(key=lambda tup: tup[0], reverse=True)
if res2[0][0] > res2[1][0] + dec_diff:
return res2[0][1]
@@ -19,7 +25,7 @@ def decide_score_stanbol(results, dec_diff):
def find_geonames2(ca, name, adm=None, **kwargs):
- headers = {'Content-Type': 'application/json'}
+ headers = {"Content-Type": "application/json"}
ca_feature = ca.stored_feature
if not ca_feature:
return False
@@ -28,17 +34,17 @@ def find_geonames2(ca, name, adm=None, **kwargs):
else:
ca_data = ca.get_data(name)
ca.get_next_feature()
- r = requests.post(ca_feature['URL'], data=json.dumps(ca_data), headers=headers)
+ r = requests.post(ca_feature["URL"], data=json.dumps(ca_data), headers=headers)
if r.status_code == 200:
res = r.json()
- if len(res['results']) == 1:
- return True, res['results'][0]
- elif len(res['results']) > 0:
- dec = decide_score_stanbol(res['results'], kwargs['dec_diff'])
+ if len(res["results"]) == 1:
+ return True, res["results"][0]
+ elif len(res["results"]) > 0:
+ dec = decide_score_stanbol(res["results"], kwargs["dec_diff"])
if dec:
return True, dec
else:
- return False, res['results']
+ return False, res["results"]
else:
return False, False
else:
@@ -50,26 +56,22 @@ def find_loc(lst, geonames_chains=False, dec_diff=5):
t = False
if not geonames_chains:
geonames_chains = []
- for c in autocomp_settings['Place']:
- geonames_chains.append(c['url'])
+ for c in autocomp_settings["Place"]:
+ geonames_chains.append(c["url"])
if len(lst) == 1:
- pl_selected_fields = StbGeoQuerySettings('place').selected
- headers = {'Content-Type': 'application/json'}
+ pl_selected_fields = StbGeoQuerySettings("place").selected
+ headers = {"Content-Type": "application/json"}
results = []
for s in geonames_chains:
ldpath = ""
for d in pl_selected_fields:
- ldpath += "{} = <{}>;\n".format(d.split('#')[-1], d)
- data = {
- 'limit': 20,
- 'name': lst[0],
- 'ldpath': ldpath
- }
+ ldpath += "{} = <{}>;\n".format(d.split("#")[-1], d)
+ data = {"limit": 20, "name": lst[0], "ldpath": ldpath}
r = requests.get(s, params=data, headers=headers)
if r.status_code == 200:
res = r.json()
- if len(res['results']) > 0:
- results.extend(res['results'])
+ if len(res["results"]) > 0:
+ results.extend(res["results"])
if len(results) > 1:
test = decide_score_stanbol(results, dec_diff=dec_diff)
if test:
@@ -82,9 +84,9 @@ def find_loc(lst, geonames_chains=False, dec_diff=5):
return False, False
elif len(lst) > 1:
for ind, c in enumerate(lst):
- if ind < len(lst)-1:
+ if ind < len(lst) - 1:
if not t:
- t = StbGeoQuerySettings('admin')
+ t = StbGeoQuerySettings("admin")
if prev_elem:
countr = find_geonames2(t, c, prev_elem, dec_diff=dec_diff)
else:
@@ -93,20 +95,31 @@ def find_loc(lst, geonames_chains=False, dec_diff=5):
while check:
if countr:
if countr[0]:
- if countr[1]['http://www.geonames.org/ontology#featureCode'][0]['value'] == 'http://www.geonames.org/ontology#A.PCLI':
+ if (
+ countr[1][
+ "http://www.geonames.org/ontology#featureCode"
+ ][0]["value"]
+ == "http://www.geonames.org/ontology#A.PCLI"
+ ):
prev_elem = (
- countr[1]['id'],
- 'http://www.geonames.org/ontology#parentCountry'
+ countr[1]["id"],
+ "http://www.geonames.org/ontology#parentCountry",
)
else:
- prev_elem = (countr[1]['id'], 'http://www.geonames.org/ontology#parent'+countr[1]['http://www.geonames.org/ontology#featureCode'][0]['value'].split('.')[-1])
+ prev_elem = (
+ countr[1]["id"],
+ "http://www.geonames.org/ontology#parent"
+ + countr[1][
+ "http://www.geonames.org/ontology#featureCode"
+ ][0]["value"].split(".")[-1],
+ )
check = False
if not countr[0]:
check = False
else:
check = False
else:
- o = StbGeoQuerySettings('place')
+ o = StbGeoQuerySettings("place")
if prev_elem:
place = find_geonames2(o, c, prev_elem, dec_diff=dec_diff)
else:
@@ -123,10 +136,11 @@ def find_loc(lst, geonames_chains=False, dec_diff=5):
def retrieve_obj(uri):
- headers = {'Content-Type': 'application/json'}
+ headers = {"Content-Type": "application/json"}
r = requests.get(
- 'http://enrich.acdh.oeaw.ac.at/entityhub/site/geoNames_S_P_A/entity',
- params={'id': uri}, headers=headers
+ "http://enrich.acdh.oeaw.ac.at/entityhub/site/geoNames_S_P_A/entity",
+ params={"id": uri},
+ headers=headers,
)
if r.status_code == 200:
return r.json()
@@ -134,22 +148,32 @@ def retrieve_obj(uri):
return False
-def query_geonames_chains(q, chains=['http://enrich.acdh.oeaw.ac.at/entityhub/site/geoNames_S_P_A/find'],
- rest_feature=['A', 'P'], dec_diff=5):
+def query_geonames_chains(
+ q,
+ chains=["http://enrich.acdh.oeaw.ac.at/entityhub/site/geoNames_S_P_A/find"],
+ rest_feature=["A", "P"],
+ dec_diff=5,
+):
results = []
ids = []
- headers = {'Content-Type': 'application/json'}
+ headers = {"Content-Type": "application/json"}
for chain in chains:
- data = {'limit': 100, 'name': q,
- 'ldpath': """name = ;
+ data = {
+ "limit": 100,
+ "name": q,
+ "ldpath": """name = ;
\nfeatureClass = ;\n
- featureCode = ;\n"""}
+ featureCode = ;\n""",
+ }
r = requests.get(chain, params=data, headers=headers)
res = r.json()
- for t in res['results']:
- if t['id'] not in ids and t['featureClass'][0]['value'].split('#')[1] in rest_feature:
+ for t in res["results"]:
+ if (
+ t["id"] not in ids
+ and t["featureClass"][0]["value"].split("#")[1] in rest_feature
+ ):
results.append(t)
- ids.append(t['id'])
+ ids.append(t["id"])
if len(results) > 0:
dec_st = decide_score_stanbol(results, dec_diff)
if dec_st:
diff --git a/apis_core/helper_functions/utils.py b/apis_core/helper_functions/utils.py
index 7467367..d7d11d5 100644
--- a/apis_core/helper_functions/utils.py
+++ b/apis_core/helper_functions/utils.py
@@ -1,4 +1,5 @@
from django.conf import settings
+from apis_core.apis_vocabularies.models import PersonPlaceRelation, PersonPersonRelation
def access_for_all(self, viewtype="list"):
@@ -22,25 +23,26 @@ def access_for_all(self, viewtype="list"):
def access_for_all_function(user):
if user.is_anonymous:
- print(getattr(settings, 'APIS_DETAIL_VIEWS_ALLOWED', False))
- return getattr(settings, 'APIS_DETAIL_VIEWS_ALLOWED', False)
+ print(getattr(settings, "APIS_DETAIL_VIEWS_ALLOWED", False))
+ return getattr(settings, "APIS_DETAIL_VIEWS_ALLOWED", False)
else:
return True
ENTITIES_DEFAULT_COLS = [
- 'start_date',
- 'start_date_written',
- 'end_date',
- 'end_date_written',
- 'text',
- 'collection',
- 'status',
- 'source',
- 'references',
- 'notes',
+ "start_date",
+ "start_date_written",
+ "end_date",
+ "end_date_written",
+ "text",
+ "collection",
+ "status",
+ "source",
+ "references",
+ "notes",
]
+
def get_child_classes(objids, obclass, labels=False):
"""used to retrieve a list of primary keys of sub classes"""
if labels:
diff --git a/apis_core/openrefine/apps.py b/apis_core/openrefine/apps.py
index fcb9887..5eb19fa 100644
--- a/apis_core/openrefine/apps.py
+++ b/apis_core/openrefine/apps.py
@@ -2,4 +2,4 @@
class OpenrefineConfig(AppConfig):
- name = 'apis_core.openrefine'
+ name = "apis_core.openrefine"
diff --git a/apis_core/openrefine/utils.py b/apis_core/openrefine/utils.py
index e8da1b8..80eb298 100644
--- a/apis_core/openrefine/utils.py
+++ b/apis_core/openrefine/utils.py
@@ -37,15 +37,20 @@ def get_service_mainfest(request, base_uri=APIS_BASE_URI, project_name=PROJECT_N
"height": 400,
},
"batchSize": 50,
- "suggest": {"type": {"service_url": f"{openrefine_uri}suggest", "service_path": "/type"}},
+ "suggest": {
+ "type": {"service_url": f"{openrefine_uri}suggest", "service_path": "/type"}
+ },
"extend": {
- "propose_properties": {"service_url": f"{openrefine_uri}properties", "service_path": ""},
+ "propose_properties": {
+ "service_url": f"{openrefine_uri}properties",
+ "service_path": "",
+ },
"property_settings": [
{
"name": "entid",
"label": "entity id",
"type": "text",
- "help_text": "entity id"
+ "help_text": "entity id",
}
],
},
diff --git a/apis_core/openrefine/views.py b/apis_core/openrefine/views.py
index 1d381a2..d1421c8 100644
--- a/apis_core/openrefine/views.py
+++ b/apis_core/openrefine/views.py
@@ -4,7 +4,14 @@
from django.views.decorators.csrf import csrf_exempt
-from apis_core.apis_entities.models import Person, Place, Institution, Work, Event, TempEntityClass
+from apis_core.apis_entities.models import (
+ Person,
+ Place,
+ Institution,
+ Work,
+ Event,
+ TempEntityClass,
+)
from .utils import get_service_mainfest, get_properties
@@ -15,7 +22,7 @@ def reconcile(request):
"place": Place,
"work": Work,
"institution": Institution,
- "event": Event
+ "event": Event,
}
if request.method == "POST":
response = {}
@@ -30,7 +37,7 @@ def reconcile(request):
query_type = value["type"]
except:
query_type = "/person"
- model_name = query_type.split('/')[-1]
+ model_name = query_type.split("/")[-1]
cur_model = model_dict[model_name]
items = cur_model.objects.filter(name=query_string)
properties = value.get("properties")
@@ -48,7 +55,10 @@ def reconcile(request):
if match_count > 1:
score = 1 / match_count
match = False
- matches = [{"id": x.id, "name": f"{x}", "score": score, "match": match} for x in items]
+ matches = [
+ {"id": x.id, "name": f"{x}", "score": score, "match": match}
+ for x in items
+ ]
item = {"result": matches}
response[key] = item
elif "extend" in data.keys():
@@ -82,7 +92,7 @@ def suggest_types(request):
print(suggestions)
filtered_results = []
for x in suggestions:
- if x['name'].startswith(prefix):
+ if x["name"].startswith(prefix):
filtered_results.append(x)
data["result"] = filtered_results
print(data)
diff --git a/apis_core/testrunners.py b/apis_core/testrunners.py
index fc3c004..3163476 100644
--- a/apis_core/testrunners.py
+++ b/apis_core/testrunners.py
@@ -145,4 +145,4 @@ def setup_databases(self, **kwargs):
else:
dict_ents[ent.__name__].append(c_1_obj)
print(f"created {c_1_obj}")
- return old_names
\ No newline at end of file
+ return old_names
diff --git a/archemd/apps.py b/archemd/apps.py
index 07446d3..db1f216 100644
--- a/archemd/apps.py
+++ b/archemd/apps.py
@@ -2,4 +2,4 @@
class ArchemdConfig(AppConfig):
- name = 'archemd'
+ name = "archemd"
diff --git a/archemd/arche_md_utils.py b/archemd/arche_md_utils.py
index 11244a3..659133c 100644
--- a/archemd/arche_md_utils.py
+++ b/archemd/arche_md_utils.py
@@ -21,7 +21,13 @@ def return_graph(self):
),
)
)
- g.add((subj, self.ARCHE["hasUrl"], Literal(self.detail_view_url, datatype=XSD.anyURI)))
+ g.add(
+ (
+ subj,
+ self.ARCHE["hasUrl"],
+ Literal(self.detail_view_url, datatype=XSD.anyURI),
+ )
+ )
else:
g.add(
(
diff --git a/archemd/urls.py b/archemd/urls.py
index 5dc55ae..732495e 100644
--- a/archemd/urls.py
+++ b/archemd/urls.py
@@ -3,5 +3,5 @@
from .views import entity_as_arche
urlpatterns = [
- path('', entity_as_arche),
+ path("", entity_as_arche),
]
diff --git a/archemd/views.py b/archemd/views.py
index 5035042..0b8f8b1 100644
--- a/archemd/views.py
+++ b/archemd/views.py
@@ -38,6 +38,4 @@ def entity_as_arche(request, pk):
res = ArcheMd(res.id)
except ObjectDoesNotExist:
return HttpResponseNotFound()
- return HttpResponse(
- res.return_graph().serialize(), content_type="text/turtle"
- )
+ return HttpResponse(res.return_graph().serialize(), content_type="text/turtle")
diff --git a/browsing/__init__.py b/browsing/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/browsing/apps.py b/browsing/apps.py
new file mode 100644
index 0000000..0d9edc1
--- /dev/null
+++ b/browsing/apps.py
@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class BrowsingConfig(AppConfig):
+ name = "browsing"
diff --git a/browsing/browsing_utils.py b/browsing/browsing_utils.py
new file mode 100644
index 0000000..d0afdfd
--- /dev/null
+++ b/browsing/browsing_utils.py
@@ -0,0 +1,214 @@
+import django_tables2
+
+from django.utils.safestring import mark_safe
+from django.views.generic.detail import DetailView
+from django.views.generic.edit import CreateView, UpdateView
+from crispy_forms.helper import FormHelper
+from crispy_forms.layout import Submit
+
+from django_tables2.export.views import ExportMixin
+
+
+input_form = """
+ |
+
+"""
+
+
+class MergeColumn(django_tables2.Column):
+ """renders a column with to checkbox - used to select objects for merging"""
+
+ def __init__(self, *args, **kwargs):
+ super(MergeColumn, self).__init__(*args, **kwargs)
+
+ def render(self, value):
+ return mark_safe(input_form.format(value, value))
+
+
+def get_entities_table(model_class):
+ class GenericEntitiesTable(django_tables2.Table):
+ id = django_tables2.LinkColumn()
+
+ class Meta:
+ model = model_class
+ attrs = {"class": "table table-hover table-striped table-condensed"}
+
+ return GenericEntitiesTable
+
+
+class GenericFilterFormHelper(FormHelper):
+ def __init__(self, *args, **kwargs):
+ super(GenericFilterFormHelper, self).__init__(*args, **kwargs)
+ self.helper = FormHelper()
+ self.form_class = "genericFilterForm"
+ self.form_method = "GET"
+ self.helper.form_tag = False
+ self.add_input(Submit("Filter", "Search"))
+
+
+class GenericListView(ExportMixin, django_tables2.SingleTableView):
+ filter_class = None
+ formhelper_class = None
+ context_filter_name = "filter"
+ paginate_by = 25
+ template_name = "browsing/generic_list.html"
+ init_columns = []
+ enable_merge = False
+ excluded_cols = []
+ verbose_name = "Personen"
+ help_text = "Personen help text"
+ icon = "bi bi-people apis-person big-icons"
+
+ def get_table_class(self):
+ if self.table_class:
+ return self.table_class
+ else:
+ return get_entities_table(self.model)
+
+ def get_all_cols(self):
+ all_cols = {
+ key: value.header for key, value in self.get_table().base_columns.items()
+ }
+ return all_cols
+
+ def get_queryset(self, **kwargs):
+ qs = super(GenericListView, self).get_queryset()
+ self.filter = self.filter_class(self.request.GET, queryset=qs)
+ self.filter.form.helper = self.formhelper_class()
+ return self.filter.qs.distinct()
+
+ def get_table(self, **kwargs):
+ table = super(GenericListView, self).get_table()
+ default_cols = self.init_columns
+ all_cols = table.base_columns.keys()
+ selected_cols = self.request.GET.getlist("columns") + default_cols
+ exclude_vals = [x for x in all_cols if x not in selected_cols]
+ table.exclude = exclude_vals
+ return table
+
+ def get_context_data(self, **kwargs):
+ context = super(GenericListView, self).get_context_data()
+ context["enable_merge"] = self.enable_merge
+ togglable_colums = {
+ key: value
+ for key, value in self.get_all_cols().items()
+ if key not in self.init_columns and key not in self.exclude_columns
+ }
+ context["togglable_colums"] = togglable_colums
+ context[self.context_filter_name] = self.filter
+ context["docstring"] = "{}".format(self.model.__doc__)
+ if self.model._meta.verbose_name_plural:
+ context["class_name"] = "{}".format(self.model._meta.verbose_name.title())
+ else:
+ if self.model.__name__.endswith("s"):
+ context["class_name"] = "{}".format(self.model.__name__)
+ else:
+ context["class_name"] = "{}s".format(self.model.__name__)
+ try:
+ context["create_view_link"] = self.model.get_createview_url()
+ except AttributeError:
+ context["create_view_link"] = None
+ model_name = self.model.__name__.lower()
+ context["entity"] = model_name
+ context["app_name"] = self.model._meta.app_label
+ context["verbose_name"] = self.verbose_name
+ context["help_text"] = self.help_text
+ context["icon"] = self.icon
+ return context
+
+
+class BaseDetailView(DetailView):
+ model = None
+ template_name = "browsing/generic_detail.html"
+
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data()
+ context["docstring"] = "{}".format(self.model.__doc__)
+ context["class_name"] = "{}".format(self.model.__name__)
+ context["app_name"] = "{}".format(self.model._meta.app_label)
+ return context
+
+
+class BaseCreateView(CreateView):
+ model = None
+ form_class = None
+ template_name = "browsing/generic_create.html"
+
+ def get_context_data(self, **kwargs):
+ context = super(BaseCreateView, self).get_context_data()
+ context["docstring"] = "{}".format(self.model.__doc__)
+ context["class_name"] = "{}".format(self.model.__name__)
+ return context
+
+
+class BaseUpdateView(UpdateView):
+ model = None
+ form_class = None
+ template_name = "browsing/generic_create.html"
+
+ def get_context_data(self, **kwargs):
+ context = super(BaseUpdateView, self).get_context_data()
+ context["docstring"] = "{}".format(self.model.__doc__)
+ context["class_name"] = "{}".format(self.model.__name__)
+ # if self.model.__name__.endswith('s'):
+ # context['class_name'] = "{}".format(self.model.__name__)
+ # else:
+ # context['class_name'] = "{}s".format(self.model.__name__)
+ return context
+
+
+def model_to_dict(instance):
+ """
+ serializes a model.object to dict, including non editable fields as well as
+ ManyToManyField fields
+ """
+ field_dicts = []
+ for x in instance._meta.get_fields():
+ f_type = "{}".format(type(x))
+ field_dict = {
+ "name": x.name,
+ "help_text": getattr(x, "help_text", ""),
+ }
+ try:
+ field_dict["extra_fields"] = x.extra
+ except AttributeError:
+ field_dict["extra_fields"] = None
+ if "reverse_related" in f_type:
+ values = getattr(instance, x.name, None)
+ if values is not None:
+ field_dict["value"] = values.all()
+ else:
+ field_dict["value"] = []
+ if getattr(x, "related_name", None) is not None:
+ field_dict["verbose_name"] = getattr(x, "related_name", x.name)
+ else:
+ field_dict["verbose_name"] = getattr(x, "verbose_name", x.name)
+ field_dict["f_type"] = "REVRESE_RELATION"
+ elif "related.ForeignKey" in f_type:
+ field_dict["verbose_name"] = getattr(x, "verbose_name", x.name)
+ field_dict["value"] = getattr(instance, x.name, "")
+ field_dict["f_type"] = "FK"
+ elif "TreeForeignKey" in f_type:
+ field_dict["verbose_name"] = getattr(x, "verbose_name", x.name)
+ field_dict["value"] = getattr(instance, x.name, "")
+ field_dict["f_type"] = "FK"
+ elif "related.ManyToManyField" in f_type:
+ values = getattr(instance, x.name, None)
+ if values is not None:
+ field_dict["value"] = values.all()
+ else:
+ field_dict["value"] = []
+ field_dict["verbose_name"] = getattr(x, "verbose_name", x.name)
+ field_dict["f_type"] = "M2M"
+ elif "fields.DateTimeField" in f_type:
+ field_value = getattr(instance, x.name, "")
+ field_dict["verbose_name"] = getattr(x, "verbose_name", x.name)
+ field_dict["f_type"] = "DateTime"
+ if field_value:
+ field_dict["value"] = field_value.strftime("%Y-%m-%d %H:%M:%S")
+ else:
+ field_dict["verbose_name"] = getattr(x, "verbose_name", x.name)
+ field_dict["value"] = f"{getattr(instance, x.name, '')}"
+ field_dict["f_type"] = "SIMPLE"
+ field_dicts.append(field_dict)
+ return field_dicts
diff --git a/browsing/migrations/0001_initial.py b/browsing/migrations/0001_initial.py
new file mode 100644
index 0000000..d652f48
--- /dev/null
+++ b/browsing/migrations/0001_initial.py
@@ -0,0 +1,51 @@
+# Generated by Django 2.2.6 on 2019-12-11 13:34
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ migrations.CreateModel(
+ name="BrowsConf",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "model_name",
+ models.CharField(
+ blank=True,
+ help_text="The name of the model class you like to analyse.",
+ max_length=255,
+ ),
+ ),
+ (
+ "label",
+ models.CharField(
+ blank=True,
+ help_text="The label of the value of interest.",
+ max_length=255,
+ ),
+ ),
+ (
+ "field_path",
+ models.CharField(
+ blank=True,
+ help_text="The constructor of to the value of interest.",
+ max_length=255,
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/browsing/migrations/0002_delete_browsconf.py b/browsing/migrations/0002_delete_browsconf.py
new file mode 100644
index 0000000..da66a33
--- /dev/null
+++ b/browsing/migrations/0002_delete_browsconf.py
@@ -0,0 +1,16 @@
+# Generated by Django 3.2 on 2021-07-21 09:48
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("browsing", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.DeleteModel(
+ name="BrowsConf",
+ ),
+ ]
diff --git a/browsing/migrations/__init__.py b/browsing/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/browsing/models.py b/browsing/models.py
new file mode 100644
index 0000000..24e1689
--- /dev/null
+++ b/browsing/models.py
@@ -0,0 +1 @@
+# from django.db import models
diff --git a/browsing/static/browsing/js/filter-for-blank-fields.js b/browsing/static/browsing/js/filter-for-blank-fields.js
new file mode 100644
index 0000000..95fc606
--- /dev/null
+++ b/browsing/static/browsing/js/filter-for-blank-fields.js
@@ -0,0 +1,15 @@
+$(function()
+{
+ var form = $( 'form' )[0];
+ $( form ).submit(function()
+ {
+ $('input, select').each(function()
+ {
+ if ($(this).val().length === 0)
+ {
+ $(this).prop('disabled', true);
+ $(this).next().prop('disabled', true);
+ }
+ });
+ });
+});
\ No newline at end of file
diff --git a/browsing/static/browsing/js/set-form-attributes.js b/browsing/static/browsing/js/set-form-attributes.js
new file mode 100644
index 0000000..fd15c6d
--- /dev/null
+++ b/browsing/static/browsing/js/set-form-attributes.js
@@ -0,0 +1,10 @@
+(function set_form_attributes() {
+ var textinput = document.getElementsByClassName('textinput');
+ for (var i = 0; i < textinput.length; i++) {
+ textinput[i].classList.add('form-control');
+ }
+ var select = document.getElementsByClassName('select');
+ for (var i = 0; i < select.length; i++) {
+ select[i].classList.add('custom-select');
+ }
+})();
\ No newline at end of file
diff --git a/browsing/templates/browsing/create_base_template.html b/browsing/templates/browsing/create_base_template.html
new file mode 100644
index 0000000..1bbf25f
--- /dev/null
+++ b/browsing/templates/browsing/create_base_template.html
@@ -0,0 +1,15 @@
+{% extends "base.html" %}
+{% block title %}{% endblock %}
+{% load crispy_forms_tags %}
+{% block content %}
+