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 class WoblinkAuthorWidget(WoblinkCatalogueWidget):
79 class AuthorForm(forms.ModelForm):
84 'woblink': WoblinkAuthorWidget,
87 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
101 list_display_links = [
102 "first_name", "last_name"
105 ("year_of_death", RangeNumericFilter),
113 ("genitive", admin.EmptyFieldListFilter)
115 list_per_page = 10000000
116 search_fields = ["first_name", "last_name", "wikidata"]
117 readonly_fields = ["wikidata_link", "description_preview", "woblink_link"]
118 prepopulated_fields = {"slug": ("first_name", "last_name")}
119 autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
127 ("wikidata", "wikidata_link"),
128 ("woblink", "woblink_link"),
135 ("first_name", "last_name"),
143 "year_of_birth_inexact",
144 "year_of_birth_range",
151 "year_of_death_inexact",
152 "year_of_death_range",
156 ("description", "description_preview"),
165 "photo", "photo_source", "photo_attribution",
171 def description_preview(self, obj):
172 return obj.generate_description()
174 def woblink_link(self, obj):
177 '<a href="https://woblink.com/autor/{slug}-{w}" target="_blank">{w}</a>',
183 woblink_link.admin_order_field = "woblink"
186 admin.site.register(models.Author, AuthorAdmin)
189 class LicenseFilter(admin.SimpleListFilter):
191 parameter_name = 'book_license'
192 license_url_field = 'document_book__dc__license'
193 license_name_field = 'document_book__dc__license_description'
195 def lookups(self, requesrt, model_admin):
199 ('pd', 'domena publiczna'),
202 def queryset(self, request, queryset):
205 return queryset.filter(**{
206 self.license_url_field + '__icontains': 'creativecommons.org'
209 return queryset.filter(**{
210 self.license_url_field + '__icontains': 'artlibre.org'
213 return queryset.filter(**{
214 self.license_name_field + '__icontains': 'domena publiczna'
220 class CoverLicenseFilter(LicenseFilter):
221 title = 'Licencja okładki'
222 parameter_name = 'cover_license'
223 license_url_field = 'document_book__dc_cover_image__license_url'
224 license_name_field = 'document_book__dc_cover_image__license_name'
227 def add_title(base_class, suffix):
228 class TitledCategoryFilter(base_class):
229 def __init__(self, *args, **kwargs):
230 super().__init__(*args, **kwargs)
232 return TitledCategoryFilter
235 class FirstPublicationYearFilter(admin.ListFilter):
236 title = 'Rok pierwszej publikacji'
237 parameter_name = 'first_publication_year'
238 template = 'admin/filter_numeric_range.html'
240 def __init__(self, request, params, *args, **kwargs):
241 super().__init__(request, params, *args, **kwargs)
243 self.request = request
245 if self.parameter_name + '_from' in params:
246 value = params.pop(self.parameter_name + '_from')
247 self.used_parameters[self.parameter_name + '_from'] = value
249 if self.parameter_name + '_to' in params:
250 value = params.pop(self.parameter_name + '_to')
251 self.used_parameters[self.parameter_name + '_to'] = value
253 def has_output(self):
256 def queryset(self, request, queryset):
259 value_from = self.used_parameters.get(self.parameter_name + '_from', None)
260 if value_from is not None and value_from != '':
262 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
265 value_to = self.used_parameters.get(self.parameter_name + '_to', None)
266 if value_to is not None and value_to != '':
268 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
271 return queryset.filter(**filters)
273 def choices(self, changelist):
275 'request': self.request,
276 'parameter_name': self.parameter_name,
277 'form': RangeNumericForm(name=self.parameter_name, data={
278 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
279 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
283 def expected_parameters(self):
285 '{}_from'.format(self.parameter_name),
286 '{}_to'.format(self.parameter_name),
290 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
302 "authors__first_name", "authors__last_name",
303 "translators__first_name", "translators__last_name",
304 "scans_source", "text_source", "notes", "estimate_source",
306 autocomplete_fields = ["authors", "translators", "based_on", "epochs", "genres", "kinds"]
307 filter_horizontal = ['collections']
308 prepopulated_fields = {"slug": ("title",)}
311 "based_on__language",
312 ("pd_year", RangeNumericFilter),
314 "collections__category",
315 ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
316 ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
317 ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
318 ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
319 "epochs", "kinds", "genres",
321 "authors__gender", "authors__nationality",
322 "translators__gender", "translators__nationality",
324 ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
325 ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
326 ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
327 ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
329 "document_book__chunk__stage",
336 FirstPublicationYearFilter,
338 list_per_page = 1000000
343 "documents_book_link",
345 "monthly_views_page",
346 "monthly_views_reader",
348 actions = [export_as_csv_action(
354 "authors_first_names",
355 "authors_last_names",
356 "translators_first_names",
357 "translators_last_names",
370 "document_book__project",
372 "first_publication_year",
374 "monthly_views_page",
375 "monthly_views_reader",
385 "chars_out_verse_with_fn",
389 (None, {"fields": [("wikidata", "wikidata_link")]}),
395 ("slug", 'documents_book_link'),
419 ("free_license", "polona_missing"),
420 ("scans_source", "scans_source_link"),
425 ("estimated_chars", "estimated_verses", "estimate_source"),
427 ("monthly_views_page", "monthly_views_reader"),
433 def get_queryset(self, request):
434 qs = super().get_queryset(request)
435 if request.resolver_match.view_name.endswith("changelist"):
436 qs = qs.prefetch_related("authors", "translators")
437 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
440 def estimated_costs(self, obj):
446 for work_type, cost in obj.get_estimated_costs().items()
449 def smart_title(self, obj):
457 '<em><small>' + escape(n) + '</small></em>'
460 smart_title.short_description = _('Title')
461 smart_title.admin_order_field = 'title'
463 def documents_book_link(self, obj):
464 for book in obj.document_books.all():
465 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))
466 documents_book_link.short_description = _('Book')
468 def scans_source_link(self, obj):
471 '<a href="{url}" target="_blank">{url}</a>',
472 url=obj.scans_source,
476 scans_source_link.short_description = _('scans source')
479 admin.site.register(models.Book, BookAdmin)
482 admin.site.register(models.CollectionCategory)
485 class AuthorInline(admin.TabularInline):
486 model = models.Author.collections.through
487 autocomplete_fields = ["author"]
490 class BookInline(admin.TabularInline):
491 model = models.Book.collections.through
492 autocomplete_fields = ["book"]
495 class CollectionAdmin(admin.ModelAdmin):
496 list_display = ["name"]
497 autocomplete_fields = []
498 prepopulated_fields = {"slug": ("name",)}
499 search_fields = ["name"]
500 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
501 readonly_fields = ['estimated_costs']
502 inlines = [AuthorInline, BookInline]
504 def estimated_costs(self, obj):
510 for work_type, cost in obj.get_estimated_costs().items()
514 admin.site.register(models.Collection, CollectionAdmin)
518 class CategoryAdmin(admin.ModelAdmin):
519 search_fields = ["name"]
521 def has_description(self, obj):
522 return bool(obj.description)
523 has_description.boolean = True
524 has_description.short_description = 'opis'
527 @admin.register(models.Epoch)
528 class EpochAdmin(CategoryAdmin):
531 'adjective_feminine_singular',
532 'adjective_nonmasculine_plural',
537 @admin.register(models.Genre)
538 class GenreAdmin(CategoryAdmin):
547 @admin.register(models.Kind)
548 class KindAdmin(CategoryAdmin):
557 class WorkRateInline(admin.TabularInline):
558 model = models.WorkRate
559 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
562 class WorkTypeAdmin(admin.ModelAdmin):
563 inlines = [WorkRateInline]
565 admin.site.register(models.WorkType, WorkTypeAdmin)
569 @admin.register(models.Place)
570 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
571 search_fields = ['name']
574 @admin.register(models.Thema)
575 class ThemaAdmin(admin.ModelAdmin):
576 list_display = ['code', 'name', 'usable', 'hidden', 'woblink_category']
577 list_filter = ['usable', 'usable_as_main', 'hidden']
578 search_fields = ['code', 'name', 'description', 'public_description']
579 prepopulated_fields = {"slug": ["name"]}
583 class WoblinkSeriesWidget(WoblinkCatalogueWidget):
586 class AudienceForm(forms.ModelForm):
588 model = models.Audience
591 'woblink': WoblinkSeriesWidget,
594 @admin.register(models.Audience)
595 class AudienceAdmin(admin.ModelAdmin):
597 list_display = ['code', 'name', 'thema', 'woblink']
598 search_fields = ['code', 'name', 'description', 'thema', 'woblink']
599 prepopulated_fields = {"slug": ["name"]}
600 fields = ['code', 'name', 'slug', 'description', 'thema', ('woblink', 'woblink_id')]
601 readonly_fields = ['woblink_id']
603 def woblink_id(self, obj):
604 return obj.woblink or ''