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.
4 from django.contrib import admin
5 from django.db.models import Min
6 from django.utils.html import escape, format_html
7 from django.utils.safestring import mark_safe
8 from django.utils.translation import gettext_lazy as _
9 from admin_numeric_filter.admin import RangeNumericFilter, NumericFilterModelAdmin, RangeNumericForm
10 from admin_ordering.admin import OrderableAdmin
11 from fnpdjango.actions import export_as_csv_action
12 from modeltranslation.admin import TabbedTranslationAdmin
14 import documents.models
15 from .wikidata import WikidataAdminMixin
18 class NotableBookInline(OrderableAdmin, admin.TabularInline):
19 model = models.NotableBook
20 autocomplete_fields = ['book']
21 ordering_field_hide_input = True
24 class AuthorAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
36 list_display_links = [
37 "first_name", "last_name"
40 ("year_of_death", RangeNumericFilter),
48 ("genitive", admin.EmptyFieldListFilter)
50 list_per_page = 10000000
51 search_fields = ["first_name", "last_name", "wikidata"]
52 readonly_fields = ["wikidata_link", "description_preview"]
55 (None, {"fields": [("wikidata", "wikidata_link")]}),
60 ("first_name", "last_name"),
68 "year_of_birth_inexact",
69 "year_of_birth_range",
76 "year_of_death_inexact",
77 "year_of_death_range",
81 ("description", "description_preview"),
90 "photo", "photo_source", "photo_attribution",
96 prepopulated_fields = {"slug": ("first_name", "last_name")}
97 autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
102 def description_preview(self, obj):
103 return obj.generate_description()
106 admin.site.register(models.Author, AuthorAdmin)
109 class LicenseFilter(admin.SimpleListFilter):
111 parameter_name = 'book_license'
112 license_url_field = 'document_book__dc__license'
113 license_name_field = 'document_book__dc__license_description'
115 def lookups(self, requesrt, model_admin):
119 ('pd', 'domena publiczna'),
122 def queryset(self, request, queryset):
125 return queryset.filter(**{
126 self.license_url_field + '__icontains': 'creativecommons.org'
129 return queryset.filter(**{
130 self.license_url_field + '__icontains': 'artlibre.org'
133 return queryset.filter(**{
134 self.license_name_field + '__icontains': 'domena publiczna'
140 class CoverLicenseFilter(LicenseFilter):
141 title = 'Licencja okładki'
142 parameter_name = 'cover_license'
143 license_url_field = 'document_book__dc_cover_image__license_url'
144 license_name_field = 'document_book__dc_cover_image__license_name'
147 def add_title(base_class, suffix):
148 class TitledCategoryFilter(base_class):
149 def __init__(self, *args, **kwargs):
150 super().__init__(*args, **kwargs)
152 return TitledCategoryFilter
155 class FirstPublicationYearFilter(admin.ListFilter):
156 title = 'Rok pierwszej publikacji'
157 parameter_name = 'first_publication_year'
158 template = 'admin/filter_numeric_range.html'
160 def __init__(self, request, params, *args, **kwargs):
161 super().__init__(request, params, *args, **kwargs)
163 self.request = request
165 if self.parameter_name + '_from' in params:
166 value = params.pop(self.parameter_name + '_from')
167 self.used_parameters[self.parameter_name + '_from'] = value
169 if self.parameter_name + '_to' in params:
170 value = params.pop(self.parameter_name + '_to')
171 self.used_parameters[self.parameter_name + '_to'] = value
173 def has_output(self):
176 def queryset(self, request, queryset):
179 value_from = self.used_parameters.get(self.parameter_name + '_from', None)
180 if value_from is not None and value_from != '':
182 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
185 value_to = self.used_parameters.get(self.parameter_name + '_to', None)
186 if value_to is not None and value_to != '':
188 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
191 return queryset.filter(**filters)
193 def choices(self, changelist):
195 'request': self.request,
196 'parameter_name': self.parameter_name,
197 'form': RangeNumericForm(name=self.parameter_name, data={
198 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
199 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
203 def expected_parameters(self):
205 '{}_from'.format(self.parameter_name),
206 '{}_to'.format(self.parameter_name),
210 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
222 "authors__first_name", "authors__last_name",
223 "translators__first_name", "translators__last_name",
224 "scans_source", "text_source", "notes", "estimate_source",
226 autocomplete_fields = ["authors", "translators", "based_on", "collections", "epochs", "genres", "kinds"]
227 prepopulated_fields = {"slug": ("title",)}
230 "based_on__language",
231 ("pd_year", RangeNumericFilter),
233 "collections__category",
234 ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
235 ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
236 ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
237 ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
238 "epochs", "kinds", "genres",
240 "authors__gender", "authors__nationality",
241 "translators__gender", "translators__nationality",
243 ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
244 ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
245 ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
246 ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
248 "document_book__chunk__stage",
255 FirstPublicationYearFilter,
257 list_per_page = 1000000
262 "documents_book_link",
264 "monthly_views_page",
265 "monthly_views_reader",
267 actions = [export_as_csv_action(
273 "authors_first_names",
274 "authors_last_names",
275 "translators_first_names",
276 "translators_last_names",
289 "document_book__project",
291 "first_publication_year",
293 "monthly_views_page",
294 "monthly_views_reader",
304 "chars_out_verse_with_fn",
308 (None, {"fields": [("wikidata", "wikidata_link")]}),
314 ("slug", 'documents_book_link'),
338 ("free_license", "polona_missing"),
339 ("scans_source", "scans_source_link"),
344 ("estimated_chars", "estimated_verses", "estimate_source"),
346 ("monthly_views_page", "monthly_views_reader"),
352 def get_queryset(self, request):
353 qs = super().get_queryset(request)
354 if request.resolver_match.view_name.endswith("changelist"):
355 qs = qs.prefetch_related("authors", "translators")
356 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
359 def estimated_costs(self, obj):
365 for work_type, cost in obj.get_estimated_costs().items()
368 def smart_title(self, obj):
376 '<em><small>' + escape(n) + '</small></em>'
379 smart_title.short_description = _('Title')
380 smart_title.admin_order_field = 'title'
382 def documents_book_link(self, obj):
383 for book in obj.document_books.all():
384 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))
385 documents_book_link.short_description = _('Book')
387 def scans_source_link(self, obj):
390 '<a href="{url}" target="_blank">{url}</a>',
391 url=obj.scans_source,
395 scans_source_link.short_description = _('scans source')
398 admin.site.register(models.Book, BookAdmin)
401 admin.site.register(models.CollectionCategory)
404 class AuthorInline(admin.TabularInline):
405 model = models.Author.collections.through
406 autocomplete_fields = ["author"]
409 class BookInline(admin.TabularInline):
410 model = models.Book.collections.through
411 autocomplete_fields = ["book"]
414 class CollectionAdmin(admin.ModelAdmin):
415 list_display = ["name"]
416 autocomplete_fields = []
417 prepopulated_fields = {"slug": ("name",)}
418 search_fields = ["name"]
419 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
420 readonly_fields = ['estimated_costs']
421 inlines = [AuthorInline, BookInline]
423 def estimated_costs(self, obj):
429 for work_type, cost in obj.get_estimated_costs().items()
433 admin.site.register(models.Collection, CollectionAdmin)
437 class CategoryAdmin(admin.ModelAdmin):
438 search_fields = ["name"]
440 def has_description(self, obj):
441 return bool(obj.description)
442 has_description.boolean = True
443 has_description.short_description = 'opis'
446 @admin.register(models.Epoch)
447 class EpochAdmin(CategoryAdmin):
450 'adjective_feminine_singular',
451 'adjective_nonmasculine_plural',
456 @admin.register(models.Genre)
457 class GenreAdmin(CategoryAdmin):
466 @admin.register(models.Kind)
467 class KindAdmin(CategoryAdmin):
476 class WorkRateInline(admin.TabularInline):
477 model = models.WorkRate
478 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
481 class WorkTypeAdmin(admin.ModelAdmin):
482 inlines = [WorkRateInline]
484 admin.site.register(models.WorkType, WorkTypeAdmin)
488 @admin.register(models.Place)
489 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
490 search_fields = ['name']
493 @admin.register(models.Thema)
494 class ThemaAdmin(admin.ModelAdmin):
495 list_display = ['code', 'name', 'usable', 'hidden']
496 list_filter = ['usable', 'hidden']
497 search_fields = ['code', 'name', 'description']