Skip to content

Commit

Permalink
feat: parler poc for Person/name
Browse files Browse the repository at this point in the history
1. modified entity form and filter set for person
2. still don't know how to set the current language for application
  • Loading branch information
gythaogg committed Nov 16, 2024
1 parent 4da62fb commit 50cfc0b
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 45 deletions.
9 changes: 6 additions & 3 deletions apis_ontology/filtersets.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.conf.global_settings import LANGUAGE_CODE
import django_filters
from apis_core.apis_entities.filtersets import (
ABSTRACT_ENTITY_FILTERS_EXCLUDE,
Expand All @@ -9,6 +10,7 @@
from apis_core.relations.models import Relation
from django.apps import apps
from django.db import models
from django.utils.translation import get_language

from apis_ontology.forms import (
PersonSearchForm,
Expand Down Expand Up @@ -212,9 +214,10 @@ class Meta:
)

def custom_name_search(self, queryset, name, value):
name_query = models.Q(name__icontains=value) | models.Q(
alternative_names__icontains=value
)
name_query = models.Q(
translations__name__icontains=value,
translations__language_code=get_language(),
) | models.Q(alternative_names__icontains=value)
if value.isdigit():
name_query = name_query | models.Q(pk=int(value))

Expand Down
8 changes: 5 additions & 3 deletions apis_ontology/forms.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from apis_core.relations.models import Relation
from apis_core.relations.forms import RelationForm
from django import forms
from apis_core.generic.forms import GenericFilterSetForm, GenericModelForm
from django.forms.models import ModelChoiceField
from django.apps import apps
from parler.fields import TranslatedField
from parler.forms import TranslatableModelForm


class TibscholEntityForm(GenericModelForm):
Expand Down Expand Up @@ -35,7 +35,9 @@ class PlaceForm(TibscholEntityForm):
]


class PersonForm(TibscholEntityForm):
class PersonForm(TranslatableModelForm, TibscholEntityForm):
name = TranslatedField()

field_order = [
"name",
"alternative_names",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Generated by Django 5.1.3 on 2024-11-15 21:53

import django.db.models.deletion
import parler.fields
import parler.models
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("apis_ontology", "0030_alter_versioninstance_options_and_more"),
]

operations = [
migrations.AlterModelOptions(
name="person",
options={},
),
migrations.AlterModelOptions(
name="versionperson",
options={
"get_latest_by": ("history_date", "history_id"),
"ordering": ("-history_date", "-history_id"),
"verbose_name": "historical person",
"verbose_name_plural": "historical persons",
},
),
migrations.RemoveField(
model_name="person",
name="name",
),
migrations.RemoveField(
model_name="versionperson",
name="name",
),
migrations.AddField(
model_name="person",
name="name_latin",
field=models.CharField(
blank=True,
default="",
editable=False,
max_length=255,
verbose_name="Name",
),
),
migrations.AddField(
model_name="versionperson",
name="name_latin",
field=models.CharField(
blank=True,
default="",
editable=False,
max_length=255,
verbose_name="Name",
),
),
migrations.CreateModel(
name="PersonTranslation",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"language_code",
models.CharField(
db_index=True, max_length=15, verbose_name="Language"
),
),
(
"name",
models.CharField(
blank=True, default="", max_length=255, verbose_name="Name"
),
),
(
"master",
parler.fields.TranslationsForeignKey(
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="translations",
to="apis_ontology.person",
),
),
],
options={
"verbose_name": "person Translation",
"db_table": "apis_ontology_person_translation",
"db_tablespace": "",
"managed": True,
"default_permissions": (),
"unique_together": {("language_code", "master")},
},
bases=(parler.models.TranslatableModel, models.Model),
),
migrations.RunSQL(
"INSERT INTO apis_ontology_person_translation(language_code, name , master_id) SELECT 'en', name_latin, rootobject_ptr_id FROM apis_ontology_person;"
),
]
23 changes: 18 additions & 5 deletions apis_ontology/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from parler.models import TranslatableModel, TranslatedFields

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -69,7 +70,12 @@ def uri(self):


class Person(
VersionMixin, LegacyStuffMixin, LegacyDateMixin, TibScholEntityMixin, AbstractEntity
VersionMixin,
LegacyStuffMixin,
LegacyDateMixin,
TibScholEntityMixin,
AbstractEntity,
TranslatableModel,
):
class_uri = "http://id.loc.gov/ontologies/bibframe/Person"

Expand All @@ -92,19 +98,26 @@ class Person(
]
NATIONALITY = [("Indic", "Indic"), ("Tibetan", "Tibetan")]

name = models.CharField(max_length=255, blank=True, default="", verbose_name="Name")
name_latin = models.CharField(
max_length=255, blank=True, default="", verbose_name="Name", editable=False
)
translations = TranslatedFields(
name=models.CharField(
max_length=255, blank=True, default="", verbose_name="Name"
)
)
gender = models.CharField(max_length=6, choices=GENDERS, default="male")
nationality = models.CharField(
max_length=10, choices=NATIONALITY, blank=True, null=True
)

def __str__(self):
return f"{self.name} ({self.pk})"

class Meta:
verbose_name = _("person")
verbose_name_plural = _("Persons")

def __str__(self):
return f"{self.name} ({self.pk})"


class Place(
E53_Place,
Expand Down
27 changes: 27 additions & 0 deletions apis_ontology/settings/server_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"apis_core.history",
"django_acdhch_functions",
"django_select2",
"parler",
]
INSTALLED_APPS.remove("apis_ontology")
INSTALLED_APPS.insert(0, "apis_ontology")
Expand Down Expand Up @@ -65,4 +66,30 @@

MIDDLEWARE += [
"simple_history.middleware.HistoryRequestMiddleware",
"django.middleware.locale.LocaleMiddleware", # Enables language switching based on session
]

LANGUAGE_CODE = "en" # This will be the default language

## List of available languages in the app
LANGUAGES = [
("en", "English"),
("bo", "Tibetan"),
]

# Locale paths (optional if you store translations in a custom directory)
# We currently use only model translations on specific fields
# LOCALE_PATHS = [
# BASE_DIR / 'locale',
# ]

PARLER_LANGUAGES = {
1: ( # Site ID 1
{"code": "en"},
{"code": "bo"},
),
"default": {
"fallback": "en", # Use English if translation is missing
"hide_untranslated": False, # Show default values for missing translations
},
}
16 changes: 16 additions & 0 deletions apis_ontology/templates/base.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{% extends "base.html" %}
{% load i18n %}

{% load static %}
{% load tibschol_entity_ctypes %}
Expand All @@ -21,6 +22,21 @@
<a class="dropdown-item" href="{{ list_url }}">{{ verbose_name_plural|capfirst }}</a>
{% endfor %}
{% endblock entities-menu-items %}
{% block userlogin-menu %}
<ul class="navbar-nav">
<li class="nav-item dropdown ml-auto">
<a href="" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">Language</a>
<div class="dropdown-menu dropdown-menu-right">
<ul>
<li class="nav-item dropdown ml-auto"><a class="nav-link" href=" {% url 'language_switcher' 'en' %}">English</a></li>
<li class="nav-item dropdown ml-auto"><a class="nav-link" href="{% url 'language_switcher' 'bo' %}">Tibetan</a></li>
</ul>
</div>
</li>
</ul>
{{ block.super }}
{% endblock userlogin-menu %}

{% block main-menu %}
<li class="nav-item dropdown">
Expand Down
18 changes: 12 additions & 6 deletions apis_ontology/urls.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
from apis_ontology.views import ExcerptsView
from apis_ontology.views import ExcerptsView, language_switcher
from django.contrib import admin
from django.urls import include, path
from django.views.generic import TemplateView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.i18n import i18n_patterns

from apis_core.apis_entities.api_views import GetEntityGeneric


urlpatterns = [
path("admin/", admin.site.urls),
path("apis/", include("apis_core.urls", namespace="apis")),
path("apis/collections/", include("apis_core.collections.urls")),
path("accounts/", include("django.contrib.auth.urls")),
path("apis/collections/", include("apis_core.collections.urls")),
path("entity/<int:pk>/", GetEntityGeneric.as_view(), name="GetEntityGenericRoot"),
path("", TemplateView.as_view(template_name="base.html")),
path(
"apis/excerpts/<str:xml_id>/<str:render_style>/",
ExcerptsView.as_view(),
name="excerpts_view",
),
path(
"switch_language/<str:language_code>/",
language_switcher,
name="language_switcher",
),
path("apis/", include("apis_core.urls", namespace="apis")),
]

# Static files and other patterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += [
path("", include("django_acdhch_functions.urls")),
]

# Additional URLs
urlpatterns += [
path("", include("django_acdhch_functions.urls")),
path("select2/", include("django_select2.urls")),
]
13 changes: 13 additions & 0 deletions apis_ontology/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from django.shortcuts import redirect
from django.utils.translation import activate
from django.http import HttpResponse
from django.views import View
from django.shortcuts import get_object_or_404
Expand All @@ -9,3 +11,14 @@ def get(self, request, xml_id, render_style, *args, **kwargs):
record = get_object_or_404(Excerpts, xml_id=xml_id)

return HttpResponse(record.xml_content)


def language_switcher(request, language_code):
# Activate the selected language
activate(language_code)

# Optionally, store the selected language in session to remember it
request.session["language"] = language_code

# Redirect back to the same page
return redirect(request.META.get("HTTP_REFERER", "/"))
Loading

0 comments on commit 50cfc0b

Please sign in to comment.