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
18 from .wikidata import WikidataAdminMixin
21 class NotableBookInline(OrderableAdmin, admin.TabularInline):
22 model = models.NotableBook
23 autocomplete_fields = ['book']
24 ordering_field_hide_input = True
27 class WoblinkCatalogueWidget(forms.Select):
30 "admin/js/vendor/jquery/jquery.min.js",
31 "admin/js/vendor/select2/select2.full.min.js",
32 "admin/js/vendor/select2/i18n/pl.js",
33 "catalogue/woblink_admin.js",
34 "admin/js/jquery.init.js",
35 "admin/js/autocomplete.js",
39 "admin/css/vendor/select2/select2.min.css",
40 "admin/css/autocomplete.css",
50 return reverse('catalogue_woblink_autocomplete', args=[self.category])
52 def build_attrs(self, base_attrs, extra_attrs=None):
53 attrs = super().build_attrs(base_attrs, extra_attrs=extra_attrs)
54 attrs.setdefault("class", "")
57 "data-ajax--cache": "true",
58 "data-ajax--delay": 250,
59 "data-ajax--type": "GET",
60 "data-ajax--url": self.get_url(),
62 "data-model-name": '',
63 "data-field-name": '',
64 "data-theme": "admin-autocomplete",
65 "data-allow-clear": json.dumps(not self.is_required),
67 "data-placeholder": "", # Chyba że znaleziony?
69 "class": attrs["class"]
70 + (" " if attrs["class"] else "")
71 + "admin-autocomplete admin-woblink",
76 def optgroups(self, name, value, attrs=None):
77 """ Add synthetic option for keeping the current value. """
87 for index, v in enumerate(value)
90 class WoblinkAuthorWidget(WoblinkCatalogueWidget):
93 class AuthorForm(forms.ModelForm):
98 'woblink': WoblinkAuthorWidget,
101 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
115 list_display_links = [
116 "first_name", "last_name"
119 ("year_of_death", RangeNumericFilter),
127 ("genitive", admin.EmptyFieldListFilter)
129 list_per_page = 10000000
130 search_fields = ["first_name", "last_name", "wikidata"]
131 readonly_fields = ["wikidata_link", "description_preview", "woblink_link"]
132 prepopulated_fields = {"slug": ("first_name", "last_name")}
133 autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
141 ("wikidata", "wikidata_link"),
142 ("woblink", "woblink_link"),
149 ("first_name", "last_name"),
157 "year_of_birth_inexact",
158 "year_of_birth_range",
165 "year_of_death_inexact",
166 "year_of_death_range",
170 ("description", "description_preview"),
179 "photo", "photo_source", "photo_attribution",
185 def description_preview(self, obj):
186 return obj.generate_description()
188 def woblink_link(self, obj):
191 '<a href="https://woblink.com/autor/{slug}-{w}" target="_blank">{w}</a>',
197 woblink_link.admin_order_field = "woblink"
200 admin.site.register(models.Author, AuthorAdmin)
203 class LicenseFilter(admin.SimpleListFilter):
205 parameter_name = 'book_license'
206 license_url_field = 'document_book__dc__license'
207 license_name_field = 'document_book__dc__license_description'
209 def lookups(self, requesrt, model_admin):
213 ('pd', 'domena publiczna'),
216 def queryset(self, request, queryset):
219 return queryset.filter(**{
220 self.license_url_field + '__icontains': 'creativecommons.org'
223 return queryset.filter(**{
224 self.license_url_field + '__icontains': 'artlibre.org'
227 return queryset.filter(**{
228 self.license_name_field + '__icontains': 'domena publiczna'
234 class CoverLicenseFilter(LicenseFilter):
235 title = 'Licencja okładki'
236 parameter_name = 'cover_license'
237 license_url_field = 'document_book__dc_cover_image__license_url'
238 license_name_field = 'document_book__dc_cover_image__license_name'
241 def add_title(base_class, suffix):
242 class TitledCategoryFilter(base_class):
243 def __init__(self, *args, **kwargs):
244 super().__init__(*args, **kwargs)
246 return TitledCategoryFilter
249 class FirstPublicationYearFilter(admin.ListFilter):
250 title = 'Rok pierwszej publikacji'
251 parameter_name = 'first_publication_year'
252 template = 'admin/filter_numeric_range.html'
254 def __init__(self, request, params, *args, **kwargs):
255 super().__init__(request, params, *args, **kwargs)
257 self.request = request
259 if self.parameter_name + '_from' in params:
260 value = params.pop(self.parameter_name + '_from')
261 self.used_parameters[self.parameter_name + '_from'] = value
263 if self.parameter_name + '_to' in params:
264 value = params.pop(self.parameter_name + '_to')
265 self.used_parameters[self.parameter_name + '_to'] = value
267 def has_output(self):
270 def queryset(self, request, queryset):
273 value_from = self.used_parameters.get(self.parameter_name + '_from', None)
274 if value_from is not None and value_from != '':
276 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
279 value_to = self.used_parameters.get(self.parameter_name + '_to', None)
280 if value_to is not None and value_to != '':
282 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
285 return queryset.filter(**filters)
287 def choices(self, changelist):
289 'request': self.request,
290 'parameter_name': self.parameter_name,
291 'form': RangeNumericForm(name=self.parameter_name, data={
292 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
293 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
297 def expected_parameters(self):
299 '{}_from'.format(self.parameter_name),
300 '{}_to'.format(self.parameter_name),
304 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
316 "authors__first_name", "authors__last_name",
317 "translators__first_name", "translators__last_name",
318 "scans_source", "text_source", "notes", "estimate_source",
320 autocomplete_fields = ["authors", "translators", "based_on", "epochs", "genres", "kinds"]
321 filter_horizontal = ['collections']
322 prepopulated_fields = {"slug": ("title",)}
325 "based_on__language",
326 ("pd_year", RangeNumericFilter),
328 "collections__category",
329 ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
330 ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
331 ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
332 ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
333 "epochs", "kinds", "genres",
335 "authors__gender", "authors__nationality",
336 "translators__gender", "translators__nationality",
338 ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
339 ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
340 ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
341 ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
343 "document_book__chunk__stage",
350 FirstPublicationYearFilter,
352 list_per_page = 1000000
357 "documents_book_link",
359 "monthly_views_page",
360 "monthly_views_reader",
362 actions = [export_as_csv_action(
368 "authors_first_names",
369 "authors_last_names",
370 "translators_first_names",
371 "translators_last_names",
384 "document_book__project",
386 "first_publication_year",
388 "monthly_views_page",
389 "monthly_views_reader",
399 "chars_out_verse_with_fn",
403 (None, {"fields": [("wikidata", "wikidata_link")]}),
409 ("slug", 'documents_book_link'),
433 ("free_license", "polona_missing"),
434 ("scans_source", "scans_source_link"),
439 ("estimated_chars", "estimated_verses", "estimate_source"),
441 ("monthly_views_page", "monthly_views_reader"),
447 def get_queryset(self, request):
448 qs = super().get_queryset(request)
449 if request.resolver_match.view_name.endswith("changelist"):
450 qs = qs.prefetch_related("authors", "translators")
451 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
454 def estimated_costs(self, obj):
460 for work_type, cost in obj.get_estimated_costs().items()
463 def smart_title(self, obj):
471 '<em><small>' + escape(n) + '</small></em>'
474 smart_title.short_description = _('Title')
475 smart_title.admin_order_field = 'title'
477 def documents_book_link(self, obj):
478 for book in obj.document_books.all():
479 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))
480 documents_book_link.short_description = _('Book')
482 def scans_source_link(self, obj):
485 '<a href="{url}" target="_blank">{url}</a>',
486 url=obj.scans_source,
490 scans_source_link.short_description = _('scans source')
493 admin.site.register(models.Book, BookAdmin)
496 admin.site.register(models.CollectionCategory)
499 class AuthorInline(admin.TabularInline):
500 model = models.Author.collections.through
501 autocomplete_fields = ["author"]
504 class BookInline(admin.TabularInline):
505 model = models.Book.collections.through
506 autocomplete_fields = ["book"]
509 class CollectionAdmin(admin.ModelAdmin):
510 list_display = ["name"]
511 autocomplete_fields = []
512 prepopulated_fields = {"slug": ("name",)}
513 search_fields = ["name"]
514 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
515 readonly_fields = ['estimated_costs']
516 inlines = [AuthorInline, BookInline]
518 def estimated_costs(self, obj):
524 for work_type, cost in obj.get_estimated_costs().items()
528 admin.site.register(models.Collection, CollectionAdmin)
532 class CategoryAdmin(admin.ModelAdmin):
533 search_fields = ["name"]
535 def has_description(self, obj):
536 return bool(obj.description)
537 has_description.boolean = True
538 has_description.short_description = 'opis'
541 @admin.register(models.Epoch)
542 class EpochAdmin(CategoryAdmin):
545 'adjective_feminine_singular',
546 'adjective_nonmasculine_plural',
551 @admin.register(models.Genre)
552 class GenreAdmin(CategoryAdmin):
561 @admin.register(models.Kind)
562 class KindAdmin(CategoryAdmin):
571 class WorkRateInline(admin.TabularInline):
572 model = models.WorkRate
573 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
576 class WorkTypeAdmin(admin.ModelAdmin):
577 inlines = [WorkRateInline]
579 admin.site.register(models.WorkType, WorkTypeAdmin)
583 @admin.register(models.Place)
584 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
585 search_fields = ['name']
588 @admin.register(models.Thema)
589 class ThemaAdmin(admin.ModelAdmin):
590 list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
591 list_filter = ['usable', 'usable_as_main', 'hidden']
592 search_fields = ['code', 'name', 'description', 'public_description']
593 prepopulated_fields = {"slug": ["name"]}
597 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
600 class AudienceForm(forms.ModelForm):
602 model = models.Audience
605 'woblink': WoblinkSeriesWidget,
608 @admin.register(models.Audience)
609 class AudienceAdmin(admin.ModelAdmin):
611 list_display = ['code', 'name', 'thema', 'woblink']
612 search_fields = ['code', 'name', 'description', 'thema', 'woblink']
613 prepopulated_fields = {"slug": ["name"]}
614 fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
615 readonly_fields = ['woblink_id']
617 def woblink_id(self, obj):
618 return obj.woblink or ''