Skip to content

Commit

Permalink
feat: parler poc for Person/name
Browse files Browse the repository at this point in the history
looks like parler's documentation is a future dream; not sure how to
make it work for existing models

References:
https://django-parler.readthedocs.io/en/stable/advanced/migrating.html
django-parler/django-parler#254
  • Loading branch information
gythaogg committed Nov 15, 2024
1 parent 4da62fb commit 3eca07d
Show file tree
Hide file tree
Showing 8 changed files with 236 additions and 40 deletions.
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;"
),
]
21 changes: 15 additions & 6 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,16 +98,19 @@ 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
)

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

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

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
22 changes: 16 additions & 6 deletions apis_ontology/urls.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
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",
),
]

# Language-aware URL patterns (wrapped in `i18n_patterns`)
urlpatterns += i18n_patterns(
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", "/"))
67 changes: 39 additions & 28 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 3eca07d

Please sign in to comment.