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'),
440 ("free_license", "polona_missing"),
441 ("scans_source", "scans_source_link"),
446 ("estimated_chars", "estimated_verses", "estimate_source"),
448 ("monthly_views_page", "monthly_views_reader"),
454 def get_queryset(self, request):
455 qs = super().get_queryset(request)
456 if request.resolver_match.view_name.endswith("changelist"):
457 qs = qs.prefetch_related("authors", "translators")
458 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
461 def estimated_costs(self, obj):
467 for work_type, cost in obj.get_estimated_costs().items()
470 def smart_title(self, obj):
478 '<em><small>' + escape(n) + '</small></em>'
481 smart_title.short_description = _('Title')
482 smart_title.admin_order_field = 'title'
484 def documents_book_link(self, obj):
485 for book in obj.document_books.all():
486 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))
487 documents_book_link.short_description = _('Book')
489 def scans_source_link(self, obj):
492 '<a href="{url}" target="_blank">{url}</a>',
493 url=obj.scans_source,
497 scans_source_link.short_description = _('scans source')
500 admin.site.register(models.Book, BookAdmin)
503 admin.site.register(models.CollectionCategory)
506 class AuthorInline(admin.TabularInline):
507 model = models.Author.collections.through
508 autocomplete_fields = ["author"]
511 class BookInline(admin.TabularInline):
512 model = models.Book.collections.through
513 autocomplete_fields = ["book"]
516 class CollectionAdmin(admin.ModelAdmin):
517 list_display = ["name"]
518 autocomplete_fields = []
519 prepopulated_fields = {"slug": ("name",)}
520 search_fields = ["name"]
521 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
522 readonly_fields = ['estimated_costs']
523 inlines = [AuthorInline, BookInline]
525 def estimated_costs(self, obj):
531 for work_type, cost in obj.get_estimated_costs().items()
535 admin.site.register(models.Collection, CollectionAdmin)
539 class CategoryAdmin(admin.ModelAdmin):
540 search_fields = ["name"]
542 def has_description(self, obj):
543 return bool(obj.description)
544 has_description.boolean = True
545 has_description.short_description = 'opis'
548 @admin.register(models.Epoch)
549 class EpochAdmin(CategoryAdmin):
552 'adjective_feminine_singular',
553 'adjective_nonmasculine_plural',
558 @admin.register(models.Genre)
559 class GenreAdmin(CategoryAdmin):
568 @admin.register(models.Kind)
569 class KindAdmin(CategoryAdmin):
578 class WorkRateInline(admin.TabularInline):
579 model = models.WorkRate
580 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
583 class WorkTypeAdmin(admin.ModelAdmin):
584 inlines = [WorkRateInline]
586 admin.site.register(models.WorkType, WorkTypeAdmin)
590 @admin.register(models.Place)
591 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
592 search_fields = ['name']
595 @admin.register(models.Thema)
596 class ThemaAdmin(admin.ModelAdmin):
597 list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
598 list_filter = ['usable', 'usable_as_main', 'hidden']
599 search_fields = ['code', 'name', 'description', 'public_description']
600 prepopulated_fields = {"slug": ["name"]}
604 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
607 class AudienceForm(forms.ModelForm):
609 model = models.Audience
612 'woblink': WoblinkSeriesWidget,
615 @admin.register(models.Audience)
616 class AudienceAdmin(admin.ModelAdmin):
618 list_display = ['code', 'name', 'thema', 'woblink']
619 search_fields = ['code', 'name', 'description', 'thema', 'woblink']
620 prepopulated_fields = {"slug": ["name"]}
621 fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
622 readonly_fields = ['woblink_id']
624 def woblink_id(self, obj):
625 return obj.woblink or ''