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.apps import apps
5 from django.db.models import Prefetch
6 from django.http import Http404
7 from django.urls import reverse
8 from django.utils.formats import localize_input
9 from django.contrib.auth.decorators import login_required
10 from django.contrib.auth.models import User
11 from django.shortcuts import get_object_or_404, redirect
12 from django.views.decorators.http import require_POST
13 from django.views.generic import DetailView, TemplateView
16 import documents.models
17 from rest_framework.generics import ListAPIView, RetrieveAPIView
18 from rest_framework.filters import SearchFilter
19 from rest_framework.permissions import IsAdminUser
20 from rest_framework.response import Response
21 from rest_framework.views import APIView
22 from rest_framework import serializers
25 class CatalogueView(TemplateView):
26 template_name = "catalogue/catalogue.html"
28 def get_context_data(self):
29 ctx = super().get_context_data()
30 ctx["authors"] = models.Author.objects.all().prefetch_related('book_set__book_set', 'translated_book_set__book_set')
35 class AuthorView(TemplateView):
37 template_name = "catalogue/author_detail.html"
39 def get_context_data(self, slug):
40 ctx = super().get_context_data()
41 authors = models.Author.objects.filter(slug=slug).prefetch_related(
43 Prefetch("translated_book_set"),
45 ctx["author"] = authors.first()
49 class BookView(DetailView):
52 class BookAPIView(RetrieveAPIView):
53 queryset = models.Book.objects.all()
56 class serializer_class(serializers.ModelSerializer):
57 class AuthorSerializer(serializers.ModelSerializer):
58 literal = serializers.CharField(source='name')
64 def category_serializer(m):
65 class CategorySerializer(serializers.ModelSerializer):
66 literal = serializers.CharField(source='name')
70 return CategorySerializer
72 authors = AuthorSerializer(many=True)
73 translators = AuthorSerializer(many=True)
74 epochs = category_serializer(models.Epoch)(many=True)
75 kinds = category_serializer(models.Kind)(many=True)
76 genres = category_serializer(models.Genre)(many=True)
94 class TermSearchFilter(SearchFilter):
98 class Terms(ListAPIView):
99 filter_backends = [TermSearchFilter]
100 search_fields = ['name']
102 class serializer_class(serializers.Serializer):
103 label = serializers.CharField(source='name')
106 class EpochTerms(Terms):
107 queryset = models.Epoch.objects.all()
108 class KindTerms(Terms):
109 queryset = models.Kind.objects.all()
110 class GenreTerms(Terms):
111 queryset = models.Genre.objects.all()
113 class AuthorTerms(Terms):
114 search_fields = ['first_name', 'last_name']
115 queryset = models.Author.objects.all()
117 class EditorTerms(Terms):
118 search_fields = ['first_name', 'last_name', 'username']
119 queryset = User.objects.all()
121 class serializer_class(serializers.Serializer):
122 label = serializers.SerializerMethodField()
124 def get_label(self, obj):
125 return f'{obj.last_name}, {obj.first_name}'
127 class BookTitleTerms(Terms):
128 queryset = models.Book.objects.all()
129 search_fields = ['title', 'slug']
131 class serializer_class(serializers.Serializer):
132 label = serializers.CharField(source='title')
134 class WLURITerms(Terms):
135 queryset = models.Book.objects.all()
136 search_fields = ['title', 'slug']
138 class serializer_class(serializers.Serializer):
139 label = serializers.CharField(source='wluri')
142 class WikidataView(APIView):
143 permission_classes = [IsAdminUser]
145 def get_object(self, model, qid, save):
147 Model = apps.get_model('catalogue', model)
150 if not issubclass(Model, models.WikidataModel):
153 obj = Model.objects.filter(wikidata=qid).first()
155 obj = Model(wikidata=qid)
156 if not obj.pk and save:
159 obj.wikidata_populate(save=False, force=True)
164 for attname in dir(Model.Wikidata):
165 if attname.startswith("_"):
167 for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
168 d[fieldname] = getattr(obj, fieldname)
170 if isinstance(d[fieldname], models.WikidataModel):
172 "model": type(d[fieldname])._meta.model_name,
173 "id": d[fieldname].pk,
174 "wd": d[fieldname].wikidata,
175 "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
177 elif hasattr(d[fieldname], 'all'):
180 "model": type(item)._meta.model_name,
183 "label": str(item) or item._wikidata_label
184 } for item in d[fieldname].all()
186 elif hasattr(d[fieldname], 'as_hint_json'):
187 d[fieldname] = d[fieldname].as_hint_json()
188 elif hasattr(d[fieldname], 'storage'):
189 d[fieldname] = d[fieldname].url if d[fieldname] else None
191 d[fieldname] = localize_input(d[fieldname])
194 def get(self, request, model, qid):
195 return self.get_object(model, qid, save=False)
197 def post(self, request, model, qid):
198 return self.get_object(model, qid, save=True)
203 def publish_author(request, pk):
204 author = get_object_or_404(models.Author, pk=pk)
206 "description_pl": author.generate_description(),
208 apiclient.api_call(request.user, f"authors/{author.slug}/", data)
209 return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
214 def publish_collection(request, pk):
215 collection = get_object_or_404(models.Collection, pk=pk)
217 "title": collection.name,
218 "description": collection.description,
219 "book_slugs": "\n".join(
221 for book in collection.book_set.exclude(slug=None).exclude(slug='')
226 f"collections/{collection.slug}/",
231 return redirect(reverse(
232 'admin:catalogue_collection_change', args=[collection.pk]