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"),
65 ("date_of_birth", "year_of_birth", "year_of_birth_inexact", "year_of_birth_range", "place_of_birth"),
66 ("date_of_death", "year_of_death", "year_of_death_inexact", "year_of_death_range", "place_of_death"),
67 ("description", "description_preview"),
76 "photo", "photo_source", "photo_attribution",
82 prepopulated_fields = {"slug": ("first_name", "last_name")}
83 autocomplete_fields = ["collections", "place_of_birth", "place_of_death"]
88 def description_preview(self, obj):
89 return obj.generate_description()
92 admin.site.register(models.Author, AuthorAdmin)
95 class LicenseFilter(admin.SimpleListFilter):
97 parameter_name = 'book_license'
98 license_url_field = 'document_book__dc__license'
99 license_name_field = 'document_book__dc__license_description'
101 def lookups(self, requesrt, model_admin):
105 ('pd', 'domena publiczna'),
108 def queryset(self, request, queryset):
111 return queryset.filter(**{
112 self.license_url_field + '__icontains': 'creativecommons.org'
115 return queryset.filter(**{
116 self.license_url_field + '__icontains': 'artlibre.org'
119 return queryset.filter(**{
120 self.license_name_field + '__icontains': 'domena publiczna'
126 class CoverLicenseFilter(LicenseFilter):
127 title = 'Licencja okładki'
128 parameter_name = 'cover_license'
129 license_url_field = 'document_book__dc_cover_image__license_url'
130 license_name_field = 'document_book__dc_cover_image__license_name'
133 def add_title(base_class, suffix):
134 class TitledCategoryFilter(base_class):
135 def __init__(self, *args, **kwargs):
136 super().__init__(*args, **kwargs)
138 return TitledCategoryFilter
141 class FirstPublicationYearFilter(admin.ListFilter):
142 title = 'Rok pierwszej publikacji'
143 parameter_name = 'first_publication_year'
144 template = 'admin/filter_numeric_range.html'
146 def __init__(self, request, params, *args, **kwargs):
147 super().__init__(request, params, *args, **kwargs)
149 self.request = request
151 if self.parameter_name + '_from' in params:
152 value = params.pop(self.parameter_name + '_from')
153 self.used_parameters[self.parameter_name + '_from'] = value
155 if self.parameter_name + '_to' in params:
156 value = params.pop(self.parameter_name + '_to')
157 self.used_parameters[self.parameter_name + '_to'] = value
159 def has_output(self):
162 def queryset(self, request, queryset):
165 value_from = self.used_parameters.get(self.parameter_name + '_from', None)
166 if value_from is not None and value_from != '':
168 self.parameter_name + '__gte': self.used_parameters.get(self.parameter_name + '_from', None),
171 value_to = self.used_parameters.get(self.parameter_name + '_to', None)
172 if value_to is not None and value_to != '':
174 self.parameter_name + '__lte': self.used_parameters.get(self.parameter_name + '_to', None),
177 return queryset.filter(**filters)
179 def choices(self, changelist):
181 'request': self.request,
182 'parameter_name': self.parameter_name,
183 'form': RangeNumericForm(name=self.parameter_name, data={
184 self.parameter_name + '_from': self.used_parameters.get(self.parameter_name + '_from', None),
185 self.parameter_name + '_to': self.used_parameters.get(self.parameter_name + '_to', None),
189 def expected_parameters(self):
191 '{}_from'.format(self.parameter_name),
192 '{}_to'.format(self.parameter_name),
196 class BookAdmin(WikidataAdminMixin, NumericFilterModelAdmin):
208 "authors__first_name", "authors__last_name",
209 "translators__first_name", "translators__last_name",
210 "scans_source", "text_source", "notes", "estimate_source",
212 autocomplete_fields = ["authors", "translators", "based_on", "collections", "epochs", "genres", "kinds"]
213 prepopulated_fields = {"slug": ("title",)}
216 "based_on__language",
217 ("pd_year", RangeNumericFilter),
219 "collections__category",
220 ("authors__collections", add_title(admin.RelatedFieldListFilter, ' autora')),
221 ("authors__collections__category", add_title(admin.RelatedFieldListFilter, ' autora')),
222 ("translators__collections", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
223 ("translators__collections__category", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
224 "epochs", "kinds", "genres",
226 "authors__gender", "authors__nationality",
227 "translators__gender", "translators__nationality",
229 ("authors__place_of_birth", add_title(admin.RelatedFieldListFilter, ' autora')),
230 ("authors__place_of_death", add_title(admin.RelatedFieldListFilter, ' autora')),
231 ("translators__place_of_birth", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
232 ("translators__place_of_death", add_title(admin.RelatedFieldListFilter, ' tłumacza')),
234 "document_book__chunk__stage",
241 FirstPublicationYearFilter,
243 list_per_page = 1000000
248 "documents_book_link",
250 "monthly_views_page",
251 "monthly_views_reader",
253 actions = [export_as_csv_action(
259 "authors_first_names",
260 "authors_last_names",
261 "translators_first_names",
262 "translators_last_names",
275 "document_book__project",
277 "first_publication_year",
279 "monthly_views_page",
280 "monthly_views_reader",
290 "chars_out_verse_with_fn",
294 (None, {"fields": [("wikidata", "wikidata_link")]}),
300 ("slug", 'documents_book_link'),
324 ("free_license", "polona_missing"),
325 ("scans_source", "scans_source_link"),
330 ("estimated_chars", "estimated_verses", "estimate_source"),
332 ("monthly_views_page", "monthly_views_reader"),
338 def get_queryset(self, request):
339 qs = super().get_queryset(request)
340 if request.resolver_match.view_name.endswith("changelist"):
341 qs = qs.prefetch_related("authors", "translators")
342 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
345 def estimated_costs(self, obj):
351 for work_type, cost in obj.get_estimated_costs().items()
354 def smart_title(self, obj):
362 '<em><small>' + escape(n) + '</small></em>'
365 smart_title.short_description = _('Title')
366 smart_title.admin_order_field = 'title'
368 def documents_book_link(self, obj):
369 for book in obj.document_books.all():
370 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))
371 documents_book_link.short_description = _('Book')
373 def scans_source_link(self, obj):
376 '<a href="{url}" target="_blank">{url}</a>',
377 url=obj.scans_source,
381 scans_source_link.short_description = _('scans source')
384 admin.site.register(models.Book, BookAdmin)
387 admin.site.register(models.CollectionCategory)
390 class AuthorInline(admin.TabularInline):
391 model = models.Author.collections.through
392 autocomplete_fields = ["author"]
395 class BookInline(admin.TabularInline):
396 model = models.Book.collections.through
397 autocomplete_fields = ["book"]
400 class CollectionAdmin(admin.ModelAdmin):
401 list_display = ["name"]
402 autocomplete_fields = []
403 prepopulated_fields = {"slug": ("name",)}
404 search_fields = ["name"]
405 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
406 readonly_fields = ['estimated_costs']
407 inlines = [AuthorInline, BookInline]
409 def estimated_costs(self, obj):
415 for work_type, cost in obj.get_estimated_costs().items()
419 admin.site.register(models.Collection, CollectionAdmin)
423 class CategoryAdmin(admin.ModelAdmin):
424 search_fields = ["name"]
426 def has_description(self, obj):
427 return bool(obj.description)
428 has_description.boolean = True
429 has_description.short_description = 'opis'
432 @admin.register(models.Epoch)
433 class EpochAdmin(CategoryAdmin):
436 'adjective_feminine_singular',
437 'adjective_nonmasculine_plural',
442 @admin.register(models.Genre)
443 class GenreAdmin(CategoryAdmin):
452 @admin.register(models.Kind)
453 class KindAdmin(CategoryAdmin):
462 class WorkRateInline(admin.TabularInline):
463 model = models.WorkRate
464 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
467 class WorkTypeAdmin(admin.ModelAdmin):
468 inlines = [WorkRateInline]
470 admin.site.register(models.WorkType, WorkTypeAdmin)
474 @admin.register(models.Place)
475 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
476 search_fields = ['name']