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.
5 from django.contrib import admin
6 from django.db.models import Min
7 from django import forms
8 from django.urls import reverse
9 from django.utils.html import escape, format_html
10 from django.utils.safestring import mark_safe
11 from django.utils.translation import gettext_lazy as _
12 from admin_numeric_filter.admin import RangeNumericFilter, NumericFilterModelAdmin, RangeNumericForm
13 from admin_ordering.admin import OrderableAdmin
14 from fnpdjango.actions import export_as_csv_action
15 from modeltranslation.admin import TabbedTranslationAdmin
16 from reversion.admin import VersionAdmin
18 import documents.models
20 from .wikidata import WikidataAdminMixin
23 class NotableBookInline(OrderableAdmin, admin.TabularInline):
24 model = models.NotableBook
25 autocomplete_fields = ['book']
26 ordering_field_hide_input = True
29 class WoblinkCatalogueWidget(forms.Select):
32 "admin/js/vendor/jquery/jquery.min.js",
33 "admin/js/vendor/select2/select2.full.min.js",
34 "admin/js/vendor/select2/i18n/pl.js",
35 "catalogue/woblink_admin.js",
36 "admin/js/jquery.init.js",
37 "admin/js/autocomplete.js",
41 "admin/css/vendor/select2/select2.min.css",
42 "admin/css/autocomplete.css",
52 return reverse('catalogue_woblink_autocomplete', args=[self.category])
54 def build_attrs(self, base_attrs, extra_attrs=None):
55 attrs = super().build_attrs(base_attrs, extra_attrs=extra_attrs)
56 attrs.setdefault("class", "")
59 "data-ajax--cache": "true",
60 "data-ajax--delay": 250,
61 "data-ajax--type": "GET",
62 "data-ajax--url": self.get_url(),
64 "data-model-name": '',
65 "data-field-name": '',
66 "data-theme": "admin-autocomplete",
67 "data-allow-clear": json.dumps(not self.is_required),
69 "data-placeholder": "", # Chyba że znaleziony?
71 "class": attrs["class"]
72 + (" " if attrs["class"] else "")
73 + "admin-autocomplete admin-woblink",
78 def optgroups(self, name, value, attrs=None):
79 """ Add synthetic option for keeping the current value. """
89 for index, v in enumerate(value)
92 class WoblinkAuthorWidget(WoblinkCatalogueWidget):
95 class AuthorForm(forms.ModelForm):
100 'woblink': WoblinkAuthorWidget,
103 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin, VersionAdmin):
117 list_display_links = [
118 "first_name", "last_name"
121 ("year_of_death", RangeNumericFilter),
129 ("genitive", admin.EmptyFieldListFilter)
131 list_per_page = 10000000
132 search_fields = ["first_name", "last_name", "wikidata"]
133 readonly_fields = ["wikidata_link", "description_preview", "woblink_link"]
134 prepopulated_fields = {"slug": ("first_name", "last_name")}
135 autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
143 ("wikidata", "wikidata_link"),
144 ("woblink", "woblink_link"),
151 ("first_name", "last_name"),
159 "year_of_birth_inexact",
160 "year_of_birth_range",
167 "year_of_death_inexact",
168 "year_of_death_range",
172 ("description", "description_preview"),
181 "photo", "photo_source", "photo_attribution",
187 def description_preview(self, obj):
188 return obj.generate_description()
190 def woblink_link(self, obj):
193 '<a href="https://woblink.com/autor/{slug}-{w}" target="_blank">{w}</a>',
199 woblink_link.admin_order_field = "woblink"
202 admin.site.register(models.Author, AuthorAdmin)
205 class LicenseFilter(admin.SimpleListFilter):
207 parameter_name = 'book_license'
208 license_url_field = 'document_book__dc__license'
209 license_name_field = 'document_book__dc__license_description'
211 def lookups(self, requesrt, model_admin):
215 ('pd', 'domena publiczna'),
218 def queryset(self, request, queryset):
221 return queryset.filter(**{
222 self.license_url_field + '__icontains': 'creativecommons.org'
225 return queryset.filter(**{
226 self.license_url_field + '__icontains': 'artlibre.org'
229 return queryset.filter(**{
230 self.license_name_field + '__icontains': 'domena publiczna'
236 class CoverLicenseFilter(LicenseFilter):
237 title = 'Licencja okładki'
238 parameter_name = 'cover_license'
239 license_url_field = 'document_book__dc_cover_image__license_url'
240 license_name_field = 'document_book__dc_cover_image__license_name'
243 class ChildrenFilter(admin.SimpleListFilter):
244 title = 'Status utworu podrzędnego'
245 parameter_name = 'book_children'
247 def lookups(self, requesrt, model_admin):
249 ('no', 'bez podrzędnych'),
250 ('only', 'tylko podrzędne'),
253 def queryset(self, request, queryset):
256 return queryset.filter(parent=None)
258 return queryset.exclude(parent=None)
263 def add_title(base_class, suffix):
264 class TitledCategoryFilter(base_class):
265 def __init__(self, *args, **kwargs):
266 super().__init__(*args, **kwargs)
268 return TitledCategoryFilter
271 class FirstPublicationYearFilter(admin.ListFilter):
272 title = 'Rok pierwszej publikacji'
273 parameter_name = 'first_publication_year'
274 template = 'admin/filter_numeric_range.html'
276 def __init__(self, request, params, *args, **kwargs):
277 super().__init__(request, params, *args, **kwargs)
279 self.request = request
281 if self.parameter_name + '_from' in params:
282 value = params.pop(self.parameter_name + '_from')
283 self.used_parameters[self.parameter_name + '_from'] = value
285 if self.parameter_name + '_to' in params:
286 value = params.pop(self.parameter_name + '_to')
287 self.used_parameters[self.parameter_name + '_to'] = value
289 def has_output(self):
292 def queryset(self, request, queryset):
295 value_from = self.used_parameters.get(self.parameter_name + '_from', None)
296 if value_from is not None and value_from != '':
298 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
301 value_to = self.used_parameters.get(self.parameter_name + '_to', None)
302 if value_to is not None and value_to != '':
304 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
307 return queryset.filter(**filters)
309 def choices(self, changelist):
311 'request': self.request,
312 'parameter_name': self.parameter_name,
313 'form': RangeNumericForm(name=self.parameter_name, data={
314 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
315 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
319 def expected_parameters(self):
321 '{}_from'.format(self.parameter_name),
322 '{}_to'.format(self.parameter_name),
326 class SourcesInline(admin.TabularInline):
327 model = sources.models.BookSource
331 class EditorNoteInline(admin.TabularInline):
332 model = models.EditorNote
336 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin, VersionAdmin):
337 inlines = [EditorNoteInline, SourcesInline]
349 "authors__first_name", "authors__last_name",
350 "translators__first_name", "translators__last_name",
351 "scans_source", "text_source", "notes", "estimate_source",
353 autocomplete_fields = ["parent", "authors", "translators", "based_on", "epochs", "genres", "kinds"]
354 filter_horizontal = ['collections']
355 prepopulated_fields = {"slug": ("title",)}
359 "based_on__language",
360 ("pd_year", RangeNumericFilter),
362 "collections__category",
363 ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
364 ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
365 ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
366 ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
367 "epochs", "kinds", "genres",
369 "authors__gender", "authors__nationality",
370 "translators__gender", "translators__nationality",
372 ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
373 ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
374 ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
375 ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
377 "document_book__chunk__stage",
384 FirstPublicationYearFilter,
386 list_per_page = 1000000
391 "documents_book_link",
393 "monthly_views_page",
394 "monthly_views_reader",
396 actions = [export_as_csv_action(
402 "authors_first_names",
403 "authors_last_names",
404 "translators_first_names",
405 "translators_last_names",
418 "document_book__project",
420 "first_publication_year",
422 "monthly_views_page",
423 "monthly_views_reader",
433 "chars_out_verse_with_fn",
437 (None, {"fields": [("wikidata", "wikidata_link")]}),
443 ("parent", "parent_number"),
444 ("slug", 'documents_book_link'),
469 ("free_license", "polona_missing"),
470 ("scans_source", "scans_source_link"),
475 ("estimated_chars", "estimated_verses", "estimate_source"),
477 ("monthly_views_page", "monthly_views_reader"),
483 def get_queryset(self, request):
484 qs = super().get_queryset(request)
485 if request.resolver_match.view_name.endswith("changelist"):
486 qs = qs.prefetch_related("authors", "translators")
487 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
490 def estimated_costs(self, obj):
496 for work_type, cost in obj.get_estimated_costs().items()
499 def smart_title(self, obj):
507 '<em><small>' + escape(n) + '</small></em>'
510 smart_title.short_description = _('Title')
511 smart_title.admin_order_field = 'title'
513 def documents_book_link(self, obj):
514 for book in obj.document_books.all():
515 return mark_safe('<a style="position: absolute" href="{}"><img height="100" width="70" src="/cover/preview/{}/?height=100&width=70"></a>'.format(book.get_absolute_url(), book.slug))
516 documents_book_link.short_description = _('Book')
518 def scans_source_link(self, obj):
521 '<a href="{url}" target="_blank">{url}</a>',
522 url=obj.scans_source,
526 scans_source_link.short_description = _('scans source')
529 admin.site.register(models.Book, BookAdmin)
532 admin.site.register(models.CollectionCategory, VersionAdmin)
535 class AuthorInline(admin.TabularInline):
536 model = models.Author.collections.through
537 autocomplete_fields = ["author"]
540 class BookInline(admin.TabularInline):
541 model = models.Book.collections.through
542 autocomplete_fields = ["book"]
545 class CollectionAdmin(VersionAdmin):
546 list_display = ["name"]
547 autocomplete_fields = []
548 prepopulated_fields = {"slug": ("name",)}
549 search_fields = ["name"]
550 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
551 readonly_fields = ['estimated_costs']
552 inlines = [AuthorInline, BookInline]
554 def estimated_costs(self, obj):
560 for work_type, cost in obj.get_estimated_costs().items()
564 admin.site.register(models.Collection, CollectionAdmin)
568 class CategoryAdmin(VersionAdmin):
569 search_fields = ["name"]
571 def has_description(self, obj):
572 return bool(obj.description)
573 has_description.boolean = True
574 has_description.short_description = 'opis'
577 @admin.register(models.Epoch)
578 class EpochAdmin(CategoryAdmin):
581 'adjective_feminine_singular',
582 'adjective_nonmasculine_plural',
587 @admin.register(models.Genre)
588 class GenreAdmin(CategoryAdmin):
607 @admin.register(models.Kind)
608 class KindAdmin(CategoryAdmin):
617 class WorkRateInline(admin.TabularInline):
618 model = models.WorkRate
619 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
622 class WorkTypeAdmin(VersionAdmin):
623 inlines = [WorkRateInline]
625 admin.site.register(models.WorkType, WorkTypeAdmin)
629 @admin.register(models.Place)
630 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin, VersionAdmin):
631 search_fields = ['name']
634 @admin.register(models.Thema)
635 class ThemaAdmin(VersionAdmin):
636 list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
637 list_filter = ['usable', 'usable_as_main', 'hidden']
638 search_fields = ['code', 'name', 'description', 'public_description']
639 prepopulated_fields = {"slug": ["name"]}
643 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
646 class AudienceForm(forms.ModelForm):
648 model = models.Audience
651 'woblink': WoblinkSeriesWidget,
654 @admin.register(models.Audience)
655 class AudienceAdmin(VersionAdmin):
657 list_display = ['code', 'name', 'thema', 'woblink']
658 search_fields = ['code', 'name', 'description', 'thema', 'woblink']
659 prepopulated_fields = {"slug": ["name"]}
660 fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
661 readonly_fields = ['woblink_id']
663 def woblink_id(self, obj):
664 return obj.woblink or ''