1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from datetime import date
5 from django.db import models
6 from django.db.models.signals import m2m_changed
7 from django.utils.html import format_html
8 from django.utils.translation import gettext_lazy as _
9 from django.dispatch import receiver
10 from wikidata.client import Client
11 from wikidata.datavalue import DatavalueError
14 class WikidataMixin(models.Model):
15 wikidata = models.CharField(
18 help_text=_('If you have a Wikidata ID, like "Q1337", enter it and save.'),
24 def save(self, **kwargs):
26 if self.wikidata and hasattr(self, "Wikidata"):
27 Wikidata = type(self).Wikidata
29 # Probably should getlist
30 entity = client.get(self.wikidata)
31 for attname in dir(Wikidata):
32 if attname.startswith("_"):
34 wd = getattr(Wikidata, attname)
36 model_field = self._meta.get_field(attname)
37 if isinstance(model_field, models.ManyToManyField):
38 if getattr(self, attname).all().exists():
41 if getattr(self, attname):
45 if wd == "description":
46 wdvalue = entity.description.get("pl", str(entity.description))
48 wdvalue = entity.label.get("pl", str(entity.label))
51 wdvalue = entity.get(client.get(wd))
52 except DatavalueError:
55 self.set_field_from_wikidata(attname, wdvalue)
57 kwargs.update(force_insert=False, force_update=True)
58 super().save(**kwargs)
60 def set_field_from_wikidata(self, attname, wdvalue):
63 # Find out what this model field is
64 model_field = self._meta.get_field(attname)
65 if isinstance(model_field, models.ForeignKey):
66 rel_model = model_field.related_model
67 if issubclass(rel_model, WikidataMixin):
68 # welp, we can try and find by WD identifier.
69 wdvalue, created = rel_model.objects.get_or_create(wikidata=wdvalue.id)
70 setattr(self, attname, wdvalue)
71 elif isinstance(model_field, models.ManyToManyField):
72 rel_model = model_field.related_model
73 if issubclass(rel_model, WikidataMixin):
74 wdvalue, created = rel_model.objects.get_or_create(wikidata=wdvalue.id)
75 getattr(self, attname).set([wdvalue])
77 # How to get original title?
78 if isinstance(wdvalue, date):
79 if isinstance(model_field, models.IntegerField):
80 wdvalue = wdvalue.year
81 elif not isinstance(wdvalue, str):
82 wdvalue = wdvalue.label.get("pl", str(wdvalue.label))
83 setattr(self, attname, wdvalue)
85 def wikidata_link(self):
88 '<a href="https://www.wikidata.org/wiki/{wd}" target="_blank">{wd}</a>',
94 wikidata_link.admin_order_field = "wikidata"
97 class WikidataAdminMixin:
98 def save_related(self, request, form, formsets, change):
99 super().save_related(request, form, formsets, change)