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
17 import documents.models
19 from .wikidata import WikidataAdminMixin
22 class NotableBookInline(OrderableAdmin, admin.TabularInline):
23 model = models.NotableBook
24 autocomplete_fields = ['book']
25 ordering_field_hide_input = True
28 class WoblinkCatalogueWidget(forms.Select):
31 "admin/js/vendor/jquery/jquery.min.js",
32 "admin/js/vendor/select2/select2.full.min.js",
33 "admin/js/vendor/select2/i18n/pl.js",
34 "catalogue/woblink_admin.js",
35 "admin/js/jquery.init.js",
36 "admin/js/autocomplete.js",
40 "admin/css/vendor/select2/select2.min.css",
41 "admin/css/autocomplete.css",
51 return reverse('catalogue_woblink_autocomplete', args=[self.category])
53 def build_attrs(self, base_attrs, extra_attrs=None):
54 attrs = super().build_attrs(base_attrs, extra_attrs=extra_attrs)
55 attrs.setdefault("class", "")
58 "data-ajax--cache": "true",
59 "data-ajax--delay": 250,
60 "data-ajax--type": "GET",
61 "data-ajax--url": self.get_url(),
63 "data-model-name": '',
64 "data-field-name": '',
65 "data-theme": "admin-autocomplete",
66 "data-allow-clear": json.dumps(not self.is_required),
68 "data-placeholder": "", # Chyba że znaleziony?
70 "class": attrs["class"]
71 + (" " if attrs["class"] else "")
72 + "admin-autocomplete admin-woblink",
77 def optgroups(self, name, value, attrs=None):
78 """ Add synthetic option for keeping the current value. """
88 for index, v in enumerate(value)
91 class WoblinkAuthorWidget(WoblinkCatalogueWidget):
94 class AuthorForm(forms.ModelForm):
99 'woblink': WoblinkAuthorWidget,
102 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
116 list_display_links = [
117 "first_name", "last_name"
120 ("year_of_death", RangeNumericFilter),
128 ("genitive", admin.EmptyFieldListFilter)
130 list_per_page = 10000000
131 search_fields = ["first_name", "last_name", "wikidata"]
132 readonly_fields = ["wikidata_link", "description_preview", "woblink_link"]
133 prepopulated_fields = {"slug": ("first_name", "last_name")}
134 autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
142 ("wikidata", "wikidata_link"),
143 ("woblink", "woblink_link"),
150 ("first_name", "last_name"),
158 "year_of_birth_inexact",
159 "year_of_birth_range",
166 "year_of_death_inexact",
167 "year_of_death_range",
171 ("description", "description_preview"),
180 "photo", "photo_source", "photo_attribution",
186 def description_preview(self, obj):
187 return obj.generate_description()
189 def woblink_link(self, obj):
192 '<a href="https://woblink.com/autor/{slug}-{w}" target="_blank">{w}</a>',
198 woblink_link.admin_order_field = "woblink"
201 admin.site.register(models.Author, AuthorAdmin)
204 class LicenseFilter(admin.SimpleListFilter):
206 parameter_name = 'book_license'
207 license_url_field = 'document_book__dc__license'
208 license_name_field = 'document_book__dc__license_description'
210 def lookups(self, requesrt, model_admin):
214 ('pd', 'domena publiczna'),
217 def queryset(self, request, queryset):
220 return queryset.filter(**{
221 self.license_url_field + '__icontains': 'creativecommons.org'
224 return queryset.filter(**{
225 self.license_url_field + '__icontains': 'artlibre.org'
228 return queryset.filter(**{
229 self.license_name_field + '__icontains': 'domena publiczna'
235 class CoverLicenseFilter(LicenseFilter):
236 title = 'Licencja okładki'
237 parameter_name = 'cover_license'
238 license_url_field = 'document_book__dc_cover_image__license_url'
239 license_name_field = 'document_book__dc_cover_image__license_name'
242 def add_title(base_class, suffix):
243 class TitledCategoryFilter(base_class):
244 def __init__(self, *args, **kwargs):
245 super().__init__(*args, **kwargs)
247 return TitledCategoryFilter
250 class FirstPublicationYearFilter(admin.ListFilter):
251 title = 'Rok pierwszej publikacji'
252 parameter_name = 'first_publication_year'
253 template = 'admin/filter_numeric_range.html'
255 def __init__(self, request, params, *args, **kwargs):
256 super().__init__(request, params, *args, **kwargs)
258 self.request = request
260 if self.parameter_name + '_from' in params:
261 value = params.pop(self.parameter_name + '_from')
262 self.used_parameters[self.parameter_name + '_from'] = value
264 if self.parameter_name + '_to' in params:
265 value = params.pop(self.parameter_name + '_to')
266 self.used_parameters[self.parameter_name + '_to'] = value
268 def has_output(self):
271 def queryset(self, request, queryset):
274 value_from = self.used_parameters.get(self.parameter_name + '_from', None)
275 if value_from is not None and value_from != '':
277 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
280 value_to = self.used_parameters.get(self.parameter_name + '_to', None)
281 if value_to is not None and value_to != '':
283 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
286 return queryset.filter(**filters)
288 def choices(self, changelist):
290 'request': self.request,
291 'parameter_name': self.parameter_name,
292 'form': RangeNumericForm(name=self.parameter_name, data={
293 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
294 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
298 def expected_parameters(self):
300 '{}_from'.format(self.parameter_name),
301 '{}_to'.format(self.parameter_name),
305 class SourcesInline(admin.TabularInline):
306 model = sources.models.BookSource
310 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
311 inlines = [SourcesInline]
323 "authors__first_name", "authors__last_name",
324 "translators__first_name", "translators__last_name",
325 "scans_source", "text_source", "notes", "estimate_source",
327 autocomplete_fields = ["authors", "translators", "based_on", "epochs", "genres", "kinds"]
328 filter_horizontal = ['collections']
329 prepopulated_fields = {"slug": ("title",)}
332 "based_on__language",
333 ("pd_year", RangeNumericFilter),
335 "collections__category",
336 ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
337 ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
338 ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
339 ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
340 "epochs", "kinds", "genres",
342 "authors__gender", "authors__nationality",
343 "translators__gender", "translators__nationality",
345 ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
346 ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
347 ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
348 ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
350 "document_book__chunk__stage",
357 FirstPublicationYearFilter,
359 list_per_page = 1000000
364 "documents_book_link",
366 "monthly_views_page",
367 "monthly_views_reader",
369 actions = [export_as_csv_action(
375 "authors_first_names",
376 "authors_last_names",
377 "translators_first_names",
378 "translators_last_names",
391 "document_book__project",
393 "first_publication_year",
395 "monthly_views_page",
396 "monthly_views_reader",
406 "chars_out_verse_with_fn",
410 (None, {"fields": [("wikidata", "wikidata_link")]}),
416 ("slug", 'documents_book_link'),
441 ("free_license", "polona_missing"),
442 ("scans_source", "scans_source_link"),
447 ("estimated_chars", "estimated_verses", "estimate_source"),
449 ("monthly_views_page", "monthly_views_reader"),
455 def get_queryset(self, request):
456 qs = super().get_queryset(request)
457 if request.resolver_match.view_name.endswith("changelist"):
458 qs = qs.prefetch_related("authors", "translators")
459 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
462 def estimated_costs(self, obj):
468 for work_type, cost in obj.get_estimated_costs().items()
471 def smart_title(self, obj):
479 '<em><small>' + escape(n) + '</small></em>'
482 smart_title.short_description = _('Title')
483 smart_title.admin_order_field = 'title'
485 def documents_book_link(self, obj):
486 for book in obj.document_books.all():
487 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))
488 documents_book_link.short_description = _('Book')
490 def scans_source_link(self, obj):
493 '<a href="{url}" target="_blank">{url}</a>',
494 url=obj.scans_source,
498 scans_source_link.short_description = _('scans source')
501 admin.site.register(models.Book, BookAdmin)
504 admin.site.register(models.CollectionCategory)
507 class AuthorInline(admin.TabularInline):
508 model = models.Author.collections.through
509 autocomplete_fields = ["author"]
512 class BookInline(admin.TabularInline):
513 model = models.Book.collections.through
514 autocomplete_fields = ["book"]
517 class CollectionAdmin(admin.ModelAdmin):
518 list_display = ["name"]
519 autocomplete_fields = []
520 prepopulated_fields = {"slug": ("name",)}
521 search_fields = ["name"]
522 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
523 readonly_fields = ['estimated_costs']
524 inlines = [AuthorInline, BookInline]
526 def estimated_costs(self, obj):
532 for work_type, cost in obj.get_estimated_costs().items()
536 admin.site.register(models.Collection, CollectionAdmin)
540 class CategoryAdmin(admin.ModelAdmin):
541 search_fields = ["name"]
543 def has_description(self, obj):
544 return bool(obj.description)
545 has_description.boolean = True
546 has_description.short_description = 'opis'
549 @admin.register(models.Epoch)
550 class EpochAdmin(CategoryAdmin):
553 'adjective_feminine_singular',
554 'adjective_nonmasculine_plural',
559 @admin.register(models.Genre)
560 class GenreAdmin(CategoryAdmin):
569 @admin.register(models.Kind)
570 class KindAdmin(CategoryAdmin):
579 class WorkRateInline(admin.TabularInline):
580 model = models.WorkRate
581 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
584 class WorkTypeAdmin(admin.ModelAdmin):
585 inlines = [WorkRateInline]
587 admin.site.register(models.WorkType, WorkTypeAdmin)
591 @admin.register(models.Place)
592 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
593 search_fields = ['name']
596 @admin.register(models.Thema)
597 class ThemaAdmin(admin.ModelAdmin):
598 list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
599 list_filter = ['usable', 'usable_as_main', 'hidden']
600 search_fields = ['code', 'name', 'description', 'public_description']
601 prepopulated_fields = {"slug": ["name"]}
605 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
608 class AudienceForm(forms.ModelForm):
610 model = models.Audience
613 'woblink': WoblinkSeriesWidget,
616 @admin.register(models.Audience)
617 class AudienceAdmin(admin.ModelAdmin):
619 list_display = ['code', 'name', 'thema', 'woblink']
620 search_fields = ['code', 'name', 'description', 'thema', 'woblink']
621 prepopulated_fields = {"slug": ["name"]}
622 fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
623 readonly_fields = ['woblink_id']
625 def woblink_id(self, obj):
626 return obj.woblink or ''