-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
781 lines (635 loc) · 30.5 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
from . import models, serializers
from django.db.models import Q, Count, Prefetch
from diana.abstract.views import DynamicDepthViewSet, GeoViewSet
from diana.abstract.models import get_fields, DEFAULT_FIELDS
from django.views.decorators.csrf import csrf_exempt
from .oai_cat import *
from django.contrib.gis.geos import Polygon
from django.contrib.gis.gdal.envelope import Envelope
from functools import reduce
from rest_framework import viewsets, status
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from collections import defaultdict
from diana.forms import ContactForm
from django.core.mail import send_mail
from django.conf import settings
class SiteViewSet(DynamicDepthViewSet):
serializer_class = serializers.SiteGeoSerializer
queryset = models.Site.objects.all()
filterset_fields = get_fields(
models.Site, exclude=DEFAULT_FIELDS + ['coordinates'])
search_fields = ['raa_id', 'lamning_id', 'ksamsok_id', 'placename']
bbox_filter_field = 'coordinates'
bbox_filter_include_overlapping = True
class SiteGeoViewSet(GeoViewSet):
serializer_class = serializers.SiteGeoSerializer
images = models.Image.objects.all()
queryset = models.Site.objects.filter(
id__in=list(images.values_list('site', flat=True))
).order_by('raa_id', 'lamning_id', 'placename')
filterset_fields = get_fields(
models.Site, exclude=DEFAULT_FIELDS + ['coordinates'])
search_fields = ['raa_id', 'lamning_id', 'ksamsok_id', 'placename']
bbox_filter_field = 'coordinates'
bbox_filter_include_overlapping = True
# Add 3D views
class SHFA3DViewSet(DynamicDepthViewSet):
serializer_class = serializers.SHFA3DSerializer
tree_d_data_group = models.Group.objects.all()
queryset = models.SHFA3D.objects.filter(
group_id__in=list(tree_d_data_group.values_list('id', flat=True)))
filterset_fields = get_fields(models.SHFA3D, exclude=DEFAULT_FIELDS)
class VisualizationGroupViewset(DynamicDepthViewSet):
serializer_class = serializers.VisualizationGroupSerializer
def get_queryset(self):
shfa3d_prefetch = Prefetch(
'shfa3d_set', queryset=models.SHFA3D.objects.all())
images_prefetch = Prefetch(
'images_set', queryset=models.Image.objects.all().order_by('subtype__order'))
queryset = models.Group.objects.all().annotate(
visualization_group_count=Count('shfa3d_set')
).prefetch_related(shfa3d_prefetch, images_prefetch)
return queryset
def get_serializer_context(self):
context = super().get_serializer_context()
depth = self.request.query_params.get('depth', 1)
try:
depth = int(depth)
except ValueError:
depth = 1
context['depth'] = depth
return context
filterset_fields = get_fields(models.Group, exclude=DEFAULT_FIELDS)
class GeologyViewSet(GeoViewSet):
serializer_class = serializers.GeologySerializer
queryset = models.Geology.objects.all()
filterset_fields = get_fields(
models.Geology, exclude=DEFAULT_FIELDS + ['coordinates', ])
class SHFA3DMeshViewset(DynamicDepthViewSet):
serializer_class = serializers.SHFA3DMeshSerializer
queryset = models.SHFA3DMesh.objects.all()
filterset_fields = get_fields(
models.SHFA3DMesh, exclude=DEFAULT_FIELDS + ['dimensions'])
class CameraSpecificationViewSet(DynamicDepthViewSet):
serializer_class = serializers.CameraSpecificationSerializer
queryset = models.CameraMeta.objects.all()
filterset_fields = get_fields(
models.CameraMeta, exclude=DEFAULT_FIELDS)
# Search views
class SiteSearchViewSet(GeoViewSet):
serializer_class = serializers.SiteGeoSerializer
def get_queryset(self):
q = self.request.GET["site_name"]
images = models.Image.objects.all()
queryset = models.Site.objects.filter(Q
(Q(raa_id__icontains=q)
| Q(lamning_id__icontains=q)
| Q(ksamsok_id__icontains=q)
| Q(placename__icontains=q)
| Q(askeladden_id__icontains=q)
| Q(lokalitet_id__icontains=q)
)
& Q
(id__in=list(images.values_list('site', flat=True)))
).order_by('raa_id', 'lamning_id', 'placename', 'ksamsok_id', 'askeladden_id', 'lokalitet_id')
return queryset
filterset_fields = get_fields(
models.Site, exclude=DEFAULT_FIELDS + ['coordinates'])
search_fields = ['raa_id', 'lamning_id', 'ksamsok_id', 'placename']
bbox_filter_field = 'coordinates'
bbox_filter_include_overlapping = True
class IIIFImageViewSet(DynamicDepthViewSet):
"""
retrieve:
Returns a single image instance.
list:
Returns a list of all the existing images in the database, paginated.
count:
Returns a count of the existing images after the application of any filter.
"""
serializer_class = serializers.TIFFImageSerializer
queryset = models.Image.objects.filter(
published=True).order_by('type__order')
filterset_fields = [
'id']+get_fields(models.Image, exclude=['created_at', 'updated_at'] + ['iiif_file', 'file'])
class NullVisualizationGroupViewset(DynamicDepthViewSet):
serializer_class = serializers.TIFFImageSerializer
queryset = models.Image.objects.filter(
group__isnull=False, published=True).order_by('type__order')
filterset_fields = [
'id']+get_fields(models.Image, exclude=['created_at', 'updated_at'] + ['iiif_file', 'file'])
class SearchBoundingBoxImageViewSet(DynamicDepthViewSet):
serializer_class = serializers.TIFFImageSerializer
def get_queryset(self):
box = self.request.GET["in_bbox"]
box = box.strip().split(',')
bbox_coords = [
float(box[0]), float(box[1]),
float(box[2]), float(box[3]),
]
bounding_box = Polygon.from_bbox((bbox_coords))
bounding_box = Envelope((bbox_coords))
sites = models.Site.objects.filter(
coordinates__intersects=bounding_box.wkt)
queryset = models.Image.objects.filter(Q(site_id__in=sites)
& Q(published=True)).order_by('type__order')
return queryset
filterset_fields = [
'id']+get_fields(models.Image, exclude=['created_at', 'updated_at'] + ['iiif_file', 'file'])
class CompilationViewset(DynamicDepthViewSet):
serializer_class = serializers.CompilationSerializer
queryset = models.Compilation.objects.all()
filterset_fields = ['id']+get_fields(models.Compilation, exclude=DEFAULT_FIELDS + [
'images__iiif_file', 'images__file'])
class SearchKeywords(DynamicDepthViewSet):
serializer_class = serializers.KeywordsSerializer
def get_queryset(self):
q = self.request.GET["keyword"]
language = self.request.GET["language"]
if language == "sv":
queryset = models.KeywordTag.objects.filter(
Q(text__icontains=q) | Q(category__icontains=q)).distinct().order_by('text', 'category')
else:
queryset = models.KeywordTag.objects.filter(Q(english_translation__icontains=q) | Q(
category_translation__icontains=q)).distinct().order_by('text', 'category')
return queryset
class SearchRockCarving(DynamicDepthViewSet):
serializer_class = serializers.RockCarvingSerializer
def get_queryset(self):
q = self.request.GET["carving_object"]
queryset = models.RockCarvingObject.objects.filter(
name__icontains=q).order_by('name')
return queryset
class SearchAuthor(DynamicDepthViewSet):
serializer_class = serializers.AuthorSerializer
def get_queryset(self):
q = self.request.GET["auhtor_name"]
images = models.Image.objects.all()
language = self.request.GET["language"]
if language == "sv":
queryset = models.Author.objects.filter(Q(name__icontains=q) &
Q(id__in=list(images.values_list('author', flat=True))
)).order_by('name')
else:
queryset = models.Author.objects.filter(Q(english_translation__icontains=q) &
Q(id__in=list(images.values_list('author', flat=True))
)).order_by('name')
return queryset
class SearchPeople(DynamicDepthViewSet):
serializer_class = serializers.PeopleSerializer
def get_queryset(self):
q = self.request.GET["auhtor_name"]
language = self.request.GET["language"]
if language == "sv":
queryset = models.People.objects.filter(
name__icontains=q).order_by('name')
else:
queryset = models.People.objects.filter(
english_translation__icontains=q).order_by('name')
return queryset
class SearchInstitution(DynamicDepthViewSet):
serializer_class = serializers.InstitutionSerializer
def get_queryset(self):
q = self.request.GET["institution_name"]
queryset = models.Institution.objects.filter(
name__icontains=q).order_by('name')
return queryset
class SearchDatinTag(DynamicDepthViewSet):
serializer_class = serializers.DatingTagSerializer
def get_queryset(self):
q = self.request.GET["dating_tag"]
language = self.request.GET["language"]
if language == "sv":
queryset = models.DatingTag.objects.filter(
text__icontains=q).order_by('text')
else:
queryset = models.DatingTag.objects.filter(
english_translation__icontains=q).order_by('text')
return queryset
class TypeSearchViewSet(DynamicDepthViewSet):
serializer_class = serializers.ImageTypeSerializer
def get_queryset(self):
q = self.request.GET["image_type"]
language = self.request.GET["language"]
if language == "sv":
queryset = models.ImageTypeTag.objects.filter(
text__icontains=q).order_by('text')
else:
queryset = models.ImageTypeTag.objects.filter(
english_translation__icontains=q).order_by('text')
return queryset
# Add general search query
class GeneralSearch(DynamicDepthViewSet):
serializer_class = serializers.TIFFImageSerializer
def get_queryset(self):
q = self.request.GET["q"]
queryset = models.Image.objects.filter(Q(dating_tags__text__icontains=q)
| Q(dating_tags__english_translation__icontains=q)
| Q(people__name__icontains=q)
| Q(people__english_translation__icontains=q)
| Q(type__text__icontains=q)
| Q(type__english_translation__icontains=q)
| Q(site__raa_id__icontains=q)
| Q(site__lamning_id__icontains=q)
| Q(site__askeladden_id__icontains=q)
| Q(site__lokalitet_id__icontains=q)
| Q(site__placename__icontains=q)
| Q(keywords__text__icontains=q)
| Q(keywords__english_translation__icontains=q)
| Q(keywords__category__icontains=q)
| Q(keywords__category_translation__icontains=q)
| Q(rock_carving_object__name__icontains=q)
| Q(institution__name__icontains=q)
).filter(published=True).distinct().order_by('-id', 'type__order')
return queryset
filterset_fields = [
'id']+get_fields(models.Image, exclude=DEFAULT_FIELDS + ['iiif_file', 'file'])
class AdvancedSearch(DynamicDepthViewSet):
serializer_class = serializers.TIFFImageSerializer
def get_queryset(self):
query_params = self.request.GET
query_conditions = []
# Define mapping between query params and model fields
field_mapping = {
"site_name": ["site__raa_id", "site__lamning_id", "site__askeladden_id",
"site__lokalitet_id", "site__placename", "site__ksamsok_id"],
"keyword": ["keywords__text", "keywords__english_translation", "keywords__category", "keywords__category_translation"],
"author_name": ["people__name", "people__english_translation"],
"dating_tag": ["dating_tags__text", "dating_tags__english_translation"],
"image_type": ["type__text", "type__english_translation"],
"institution_name": ["institution__name"]
}
for param, fields in field_mapping.items():
if param in query_params:
value = query_params[param]
# Creating OR conditions for each field
or_conditions = [Q(**{field + '__icontains': value})
for field in fields]
query_conditions.append(
reduce(lambda x, y: x | y, or_conditions))
if not query_conditions:
# Handle no query parameters provided
# You might want to raise an error or return an empty queryset
# For now, returning an empty queryset
return models.Image.objects.none()
queryset = models.Image.objects.filter(reduce(
lambda x, y: x & y, query_conditions), published=True).order_by('-id', 'type__order')
return queryset
filterset_fields = [
'id'] + get_fields(models.Image, exclude=DEFAULT_FIELDS + ['iiif_file', 'file'])
# Add gallery view
class GalleryViewSet(DynamicDepthViewSet):
queryset = models.Image.objects.filter(published=True).order_by('type__order')
serializer_class = serializers.TIFFImageSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['id'] + get_fields(models.Image, exclude=DEFAULT_FIELDS + ['iiif_file', 'file'])
def list(self, request, *args, **kwargs):
"""Handles GET requests, returning paginated image results with summary by creator and institution."""
search_type = request.GET.get("search_type")
box = request.GET.get("in_bbox")
site = request.GET.get("site")
category_type = request.GET.get("category_type")
if not search_type and not box and not site and not category_type:
return Response([])
queryset = self.queryset
# Apply site filter
if site:
queryset = queryset.filter(site_id=site)
# Apply bbox filter
if box:
box = list(map(float, box.strip().split(',')))
bounding_box = Envelope(box) # Assuming spatial filtering
sites = models.Site.objects.filter(coordinates__intersects=bounding_box.wkt)
queryset = queryset.filter(site_id__in=sites)
# Apply search types
elif search_type == "advanced":
queryset = self.get_advanced_search_queryset()
elif search_type == "general":
queryset = self.get_general_search_queryset()
else:
queryset = self.filter_queryset(self.get_queryset())
# Apply image type filter
if category_type:
queryset = queryset.filter(type__text=category_type)
else:
# Categorize images by type
categorized_data = self.categorize_by_type(queryset)
return Response({
"results": categorized_data,
})
# Generate summary BEFORE pagination
summary_data = self.summarize_results(queryset)
# Apply pagination
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
paginated_response = self.get_paginated_response(serializer.data)
return paginated_response
# If pagination is disabled, return full results with summary
serializer = self.get_serializer(queryset, many=True)
return Response({
"results": serializer.data,
})
def categorize_by_type(self, queryset):
"""Groups queryset results by `type__text` with counts and limits images to 5 per type."""
# Step 1: Group data by type with translation and count
grouped_data = (
queryset
.values("type__id", "type__text", "type__english_translation")
.annotate(img_count=Count("id", distinct=True)) # Ensure unique counting
.order_by("type__id"))
# Step 2: Prepare dictionary for categories
category_dict = {
entry["type__id"]: {
"type": entry["type__text"],
"type_translation": entry.get("type__english_translation", "Unknown"),
"count": entry["img_count"],
"images": [],
}
for entry in grouped_data
}
# Step 3: Fetch images but limit to 5 per type
limited_images = (
queryset
.values()
.order_by("type_id", "id")
)
# Step 4: Assign images to categories with a limit of 5 per type
image_count_per_category = defaultdict(int)
for img in limited_images:
type_id = img["type_id"]
if type_id in category_dict and image_count_per_category[type_id] < 5:
category_dict[type_id]["images"].append(img)
image_count_per_category[type_id] += 1
# Step 3: Convert dictionary to list format
return list(category_dict.values())
def get_advanced_search_queryset(self):
"""Handles advanced search with query parameters."""
query_params = self.request.GET
query_conditions = []
field_mapping = {
"site_name": ["site__raa_id", "site__lamning_id", "site__askeladden_id",
"site__lokalitet_id", "site__placename", "site__ksamsok_id"],
"keyword": ["keywords__text", "keywords__english_translation", "keywords__category", "keywords__category_translation"],
"author_name": ["people__name", "people__english_translation"],
"dating_tag": ["dating_tags__text", "dating_tags__english_translation"],
"image_type": ["type__text", "type__english_translation"],
"institution_name": ["institution__name"]
}
for param, fields in field_mapping.items():
if param in query_params:
value = query_params[param]
or_conditions = [Q(**{f"{field}__icontains": value}) for field in fields]
query_conditions.append(reduce(lambda x, y: x | y, or_conditions))
if not query_conditions:
return self.queryset.none()
return self.queryset.filter(reduce(lambda x, y: x & y, query_conditions), published=True).order_by('type__order')
def get_general_search_queryset(self):
"""Handles general search with 'q' parameter."""
q = self.request.GET.get("q", "")
if not q:
return self.queryset.none()
return self.queryset.filter(
Q(dating_tags__text__icontains=q)
| Q(dating_tags__english_translation__icontains=q)
| Q(people__name__icontains=q)
| Q(people__english_translation__icontains=q)
| Q(type__text__icontains=q)
| Q(type__english_translation__icontains=q)
| Q(site__raa_id__icontains=q)
| Q(site__lamning_id__icontains=q)
| Q(site__askeladden_id__icontains=q)
| Q(site__lokalitet_id__icontains=q)
| Q(site__placename__icontains=q)
| Q(keywords__text__icontains=q)
| Q(keywords__english_translation__icontains=q)
| Q(keywords__category__icontains=q)
| Q(keywords__category_translation__icontains=q)
| Q(rock_carving_object__name__icontains=q)
| Q(institution__name__icontains=q)
).filter(published=True).order_by('-id', 'type__order').distinct()
class SummaryViewSet(DynamicDepthViewSet):
"""A separate viewset to return summary data for images grouped by creator and institution and etc."""
queryset = models.Image.objects.filter(published=True).order_by('type__order')
serializer_class = serializers.SummarySerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['id'] + get_fields(models.Image, exclude=DEFAULT_FIELDS + ['iiif_file', 'file'])
def list(self, request, *args, **kwargs):
"""Handles GET requests, returning paginated image results with summary by creator and institution."""
search_type = request.GET.get("search_type")
box = request.GET.get("in_bbox")
site = request.GET.get("site")
queryset = self.queryset
# Apply site filter
if site:
queryset = queryset.filter(site_id=site)
# Apply bbox filter
if box:
box = list(map(float, box.strip().split(',')))
bounding_box = Envelope(box) # Assuming spatial filtering
sites = models.Site.objects.filter(coordinates__intersects=bounding_box.wkt)
queryset = queryset.filter(site_id__in=sites)
# Apply search types
elif search_type == "advanced":
queryset = self.get_advanced_search_queryset()
elif search_type == "general":
queryset = self.get_general_search_queryset()
else:
queryset = self.filter_queryset(self.get_queryset())
# Generate summary BEFORE pagination
summary_data = self.summarize_results(queryset)
return Response(summary_data)
def summarize_results(self, queryset):
"""Summarizes search results by creator and institution."""
# we should add Summarise search results by geographic data too: TODO
# Summarise by ADM0, ADM1, ADM2, socken, kommun, landskap/län: TODO
# motif: Two level summary with keyword categories and subcategories: Done
# Count of documentation types by site: Done
# Show number of images for each year: Done
# Summarise search results by creator and institution : Done
summary = {
"creators": [],
"institutions": [],
"year": [],
"types": [],
"motifs": [],
"geographic": [],
"site": []
}
# Count images per creator
creator_counts = (
queryset
.values("people__name")
.annotate(count=Count("id", distinct=True))
.order_by("-count")
)
# Count images per institution
institution_counts = (
queryset
.values("institution__name")
.annotate(count=Count("id", distinct=True))
.order_by("-count")
)
# Count of documentation types by site
type_counts = (
queryset
.values("type__text")
.annotate(count=Count("id", distinct=True))
.order_by("-count")
)
# Summarise search results by motif type
motif_counts = (
queryset
.values("keywords__text")
.annotate(count=Count("id", distinct=True))
.order_by("-count")
)
# Show number of images for each year
year_counts = (
queryset
.values("year")
.annotate(count=Count("id", distinct=True))
.order_by("year")
)
site_counts = (
queryset
.values("site__raa_id", "site__lamning_id", "site__askeladden_id",
"site__lokalitet_id", "site__placename", "site__ksamsok_id")
.annotate(count=Count("id", distinct=True))
.order_by("-count")
)
# Gorgraphic summary can be a json object with counts for each level of geographic data
# ADM0, ADM1, ADM2, socken, kommun, landskap/län
geographic_counts = (
queryset
.values("site__municipality__name", "site__parish__name", "site__province__name", "site__province__country__name")
.annotate(count=Count("id", distinct=True))
.order_by("-count")
)
# Format summary
summary["creators"] = [
{"creator": entry["people__name"], "count": entry["count"]}
for entry in creator_counts if entry["people__name"]
]
summary["site"] = [
{"site": entry["site__raa_id"], "count": entry["count"]}
for entry in site_counts if entry["site__raa_id"]
]
summary["institutions"] = [
{"institution": entry["institution__name"], "count": entry["count"]}
for entry in institution_counts if entry["institution__name"]
]
summary["types"] = [
{"type": entry["type__text"], "count": entry["count"]}
for entry in type_counts if entry["type__text"]
]
summary["motifs"] = [
{"motif": entry["keywords__text"], "count": entry["count"]}
for entry in motif_counts
if "figures" in "image__keywords__category_translation"
and entry["keywords__text"] not in ["Cupmarks", "Line", "Indeterminate figure",
"Memorial inscription", "Historic carving",
"Brev", "Later carving"]
]
summary["year"] = [
{"year": entry["year"], "count": entry["count"]}
for entry in year_counts if entry["year"]
]
summary["geographic"] = [
{
"municipality": entry["site__municipality__name"],
"parish": entry["site__parish__name"],
"province": entry["site__province__name"],
"country": entry["site__province__country__name"],
"count": entry["count"]
}
for entry in geographic_counts
]
return summary
def get_advanced_search_queryset(self):
"""Handles advanced search with query parameters."""
query_params = self.request.GET
query_conditions = []
field_mapping = {
"site_name": ["site__raa_id", "site__lamning_id", "site__askeladden_id",
"site__lokalitet_id", "site__placename", "site__ksamsok_id"],
"keyword": ["keywords__text", "keywords__english_translation", "keywords__category", "keywords__category_translation"],
"author_name": ["people__name", "people__english_translation"],
"dating_tag": ["dating_tags__text", "dating_tags__english_translation"],
"image_type": ["type__text", "type__english_translation"],
"institution_name": ["institution__name"]
}
for param, fields in field_mapping.items():
if param in query_params:
value = query_params[param]
or_conditions = [Q(**{f"{field}__icontains": value}) for field in fields]
query_conditions.append(reduce(lambda x, y: x | y, or_conditions))
if not query_conditions:
return self.queryset.none()
return self.queryset.filter(reduce(lambda x, y: x & y, query_conditions), published=True).order_by('type__order')
def get_general_search_queryset(self):
"""Handles general search with 'q' parameter."""
q = self.request.GET.get("q", "")
if not q:
return self.queryset.none()
return self.queryset.filter(
Q(dating_tags__text__icontains=q)
| Q(dating_tags__english_translation__icontains=q)
| Q(people__name__icontains=q)
| Q(people__english_translation__icontains=q)
| Q(type__text__icontains=q)
| Q(type__english_translation__icontains=q)
| Q(site__raa_id__icontains=q)
| Q(site__lamning_id__icontains=q)
| Q(site__askeladden_id__icontains=q)
| Q(site__lokalitet_id__icontains=q)
| Q(site__placename__icontains=q)
| Q(keywords__text__icontains=q)
| Q(keywords__english_translation__icontains=q)
| Q(keywords__category__icontains=q)
| Q(keywords__category_translation__icontains=q)
| Q(rock_carving_object__name__icontains=q)
| Q(institution__name__icontains=q)
).filter(published=True).order_by('-id', 'type__order').distinct()
# VIEW FOR OAI_CAT
@csrf_exempt
def oai(request):
params = request.POST.copy() if request.method == "POST" else request.GET.copy()
verb = None
if "verb" in params:
verb = params.pop("verb")[-1]
if verb == "GetRecord":
output = get_records(params, request)
elif verb == "Identify":
output = get_identify(request)
elif verb == "ListRecords":
output = get_list_records(verb, request, params)
elif verb == "ListMetadataFormats":
output = get_list_metadata(request, params)
else:
output = verb_error(request)
return output
# Add contact form view
class ContactFormViewSet(viewsets.ViewSet):
def create(self, request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
# Send an email
send_mail(
f'From {name}, Subject: {subject}',
f'Message: {message}\n',
email, # From email
[settings.EMAIL_HOST_USER], # To email
fail_silently=False,
)
return Response({'message': 'Email sent successfully'}, status=status.HTTP_200_OK)
else:
form = ContactForm()
return Response({'error': 'Invalid request method'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)