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",
276 "first_publication_year",
278 "monthly_views_page",
279 "monthly_views_reader",
289 "chars_out_verse_with_fn",
293 (None, {"fields": [("wikidata", "wikidata_link")]}),
299 ("slug", 'documents_book_link'),
323 ("free_license", "polona_missing"),
324 ("scans_source", "scans_source_link"),
329 ("estimated_chars", "estimated_verses", "estimate_source"),
331 ("monthly_views_page", "monthly_views_reader"),
337 def get_queryset(self, request):
338 qs = super().get_queryset(request)
339 if request.resolver_match.view_name.endswith("changelist"):
340 qs = qs.prefetch_related("authors", "translators")
341 qs = qs.annotate(first_publication_year=Min('document_book__publish_log__timestamp__year'))
344 def estimated_costs(self, obj):
350 for work_type, cost in obj.get_estimated_costs().items()
353 def smart_title(self, obj):
361 '<em><small>' + escape(n) + '</small></em>'
364 smart_title.short_description = _('Title')
365 smart_title.admin_order_field = 'title'
367 def documents_book_link(self, obj):
368 for book in obj.document_books.all():
369 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))
370 documents_book_link.short_description = _('Book')
372 def scans_source_link(self, obj):
375 '<a href="{url}" target="_blank">{url}</a>',
376 url=obj.scans_source,
380 scans_source_link.short_description = _('scans source')
383 admin.site.register(models.Book, BookAdmin)
386 admin.site.register(models.CollectionCategory)
389 class AuthorInline(admin.TabularInline):
390 model = models.Author.collections.through
391 autocomplete_fields = ["author"]
394 class BookInline(admin.TabularInline):
395 model = models.Book.collections.through
396 autocomplete_fields = ["book"]
399 class CollectionAdmin(admin.ModelAdmin):
400 list_display = ["name"]
401 autocomplete_fields = []
402 prepopulated_fields = {"slug": ("name",)}
403 search_fields = ["name"]
404 fields = ['name', 'slug', 'category', 'description', 'notes', 'estimated_costs']
405 readonly_fields = ['estimated_costs']
406 inlines = [AuthorInline, BookInline]
408 def estimated_costs(self, obj):
414 for work_type, cost in obj.get_estimated_costs().items()
418 admin.site.register(models.Collection, CollectionAdmin)
422 class CategoryAdmin(admin.ModelAdmin):
423 search_fields = ["name"]
425 def has_description(self, obj):
426 return bool(obj.description)
427 has_description.boolean = True
428 has_description.short_description = 'opis'
431 @admin.register(models.Epoch)
432 class EpochAdmin(CategoryAdmin):
435 'adjective_feminine_singular',
436 'adjective_nonmasculine_plural',
441 @admin.register(models.Genre)
442 class GenreAdmin(CategoryAdmin):
451 @admin.register(models.Kind)
452 class KindAdmin(CategoryAdmin):
461 class WorkRateInline(admin.TabularInline):
462 model = models.WorkRate
463 autocomplete_fields = ['kinds', 'genres', 'epochs', 'collections']
466 class WorkTypeAdmin(admin.ModelAdmin):
467 inlines = [WorkRateInline]
469 admin.site.register(models.WorkType, WorkTypeAdmin)
473 @admin.register(models.Place)
474 class PlaceAdmin(WikidataAdminMixin, TabbedTranslationAdmin):
475 search_fields = ['name']