-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathserializers.py
More file actions
2149 lines (1789 loc) · 70.6 KB
/
serializers.py
File metadata and controls
2149 lines (1789 loc) · 70.6 KB
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import re
from urllib.parse import parse_qs, urlparse
import bleach
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.validators import URLValidator
from django.db import models
from django.db.models import Prefetch
from django.template.defaultfilters import slugify
from django.utils import timezone
from rest_framework import serializers, validators
from simple_history.utils import update_change_reason
from clubs.mixins import ManyToManySaveMixin
from clubs.models import (
Advisor,
Asset,
Badge,
Club,
ClubApplication,
ClubFair,
ClubVisit,
Event,
Favorite,
Major,
Membership,
MembershipInvite,
MembershipRequest,
Note,
NoteTag,
Profile,
QuestionAnswer,
Report,
School,
SearchQuery,
StudentType,
Subscribe,
Tag,
Testimonial,
Year,
)
from clubs.utils import clean
ALL_TAGS_SELECTED_ERROR_MESSAGE = (
(
"We noticed you selected all of the options "
"for one or more of the previous tags. "
"In order to best optimize our sorting algorithm, "
"you need to select only the few "
"tags that apply to your resource. "
"If you feel that all the tags apply, that's great! "
"In that case you would select 'Yes' to the "
"question asking if your resource applies to "
"all undergraduate, graduate, and professional Penn students. "
"Thanks for doing your part to ensure that Hub@Penn "
"quickly and efficiently gets resources to our Penn community. "
)
if settings.BRANDING == "fyh"
else (
"You should not select all of the items in this list. "
"If all of these items apply, select none of them instead."
)
)
class ClubRouteMixin(object):
"""
Mixin for serializers that overrides the save method to
properly handle the URL parameter for club.
"""
def save(self):
self.validated_data["club"] = Club.objects.get(
code=self.context["view"].kwargs.get("club_code")
)
return super().save()
class TagSerializer(serializers.ModelSerializer):
clubs = serializers.IntegerField(read_only=True)
class Meta:
model = Tag
fields = ("id", "name", "clubs")
class BadgeSerializer(serializers.ModelSerializer):
purpose = serializers.CharField(read_only=True)
class Meta:
model = Badge
fields = ("id", "purpose", "label", "color", "description")
class SchoolSerializer(serializers.ModelSerializer):
name = serializers.CharField()
is_graduate = serializers.BooleanField(read_only=True)
class Meta:
model = School
fields = ("id", "name", "is_graduate")
class MajorSerializer(serializers.ModelSerializer):
name = serializers.CharField()
class Meta:
model = Major
fields = ("id", "name")
class TestimonialSerializer(ClubRouteMixin, serializers.ModelSerializer):
text = serializers.CharField()
class Meta:
model = Testimonial
fields = ("id", "text")
class QuestionAnswerSerializer(ClubRouteMixin, serializers.ModelSerializer):
author = serializers.SerializerMethodField("get_author_name")
responder = serializers.SerializerMethodField("get_responder_name")
is_anonymous = serializers.BooleanField(write_only=True)
def get_author_name(self, obj):
user = self.context["request"].user
if obj.author == user:
return "{} (Anonymous)".format(obj.author.get_full_name())
if obj.is_anonymous or obj.author is None:
return "Anonymous"
return obj.author.get_full_name()
def get_responder_name(self, obj):
if obj.responder is None:
return obj.club.name
return obj.responder.get_full_name()
def validate_question(self, value):
"""
The club owner is not allowed to edit the user's question.
Users are not allowed to edit their question after it has
been responded to.
"""
if not self.instance:
return value
if not value == self.instance.question:
user = self.context["request"].user
if not user == self.instance.author:
raise serializers.ValidationError(
"You are not allowed to edit the author's question!"
)
if self.instance.answer:
raise serializers.ValidationError(
"You are not allowed to edit the question "
"after an answer has been given!"
)
return value
def validate_is_anonymous(self, value):
"""
Only the author should be able to change the status of their post's anonymity.
"""
if not self.instance:
return value
if not value == self.instance.is_anonymous:
user = self.context["request"].user
if not user == self.instance.author:
raise serializers.ValidationError(
"You are not allowed to change the anonymity status of this post!"
)
return value
def validate_answer(self, value):
"""
Only a club officer may respond to a question.
An answer may not be set to null after it has been answered.
"""
if value is None:
if self.instance and self.instance.answer is not None:
raise serializers.ValidationError(
"You are not allowed to unanswer a question! "
+ "You can change the answer text instead."
)
return value
value = clean(bleach.linkify(value))
club = Club.objects.get(code=self.context["view"].kwargs.get("club_code"))
user = self.context["request"].user
if user.is_superuser:
return value
membership = Membership.objects.filter(person=user, club=club).first()
if membership is not None and membership.role <= Membership.ROLE_OFFICER:
return value
raise serializers.ValidationError(
"You are not allowed to answer this question!"
)
def update(self, instance, validated_data):
"""
If the question or answer has changed, set the new author appropriately.
"""
user = self.context["request"].user
if (
"question" in validated_data
and not validated_data["question"] == instance.question
):
validated_data["author"] = user
if (
"answer" in validated_data
and not validated_data["answer"] == instance.answer
):
validated_data["responder"] = user
validated_data["approved"] = True
return super().update(instance, validated_data)
def create(self, validated_data):
"""
Set the author of the question to the current user.
Send out an email to officers and above notifying them of this question.
"""
validated_data["author"] = self.context["request"].user
obj = super().create(validated_data)
obj.send_question_mail(self.context["request"])
return obj
class Meta:
model = QuestionAnswer
fields = (
"id",
"question",
"answer",
"author",
"responder",
"is_anonymous",
"approved",
)
class ReportSerializer(serializers.ModelSerializer):
creator = serializers.SerializerMethodField("get_creator")
def get_creator(self, obj):
return obj.creator.get_full_name()
def create(self, validated_data):
"""
Set the creator of the report to the current user.
If a report with the same name and creator exists,
overwrite that report instead.
"""
return Report.objects.update_or_create(
name=validated_data.pop("name"),
creator=self.context["request"].user,
defaults=validated_data,
)[0]
class Meta:
model = Report
fields = (
"id",
"name",
"creator",
"description",
"parameters",
"created_at",
"updated_at",
"public",
)
class YearSerializer(serializers.ModelSerializer):
name = serializers.CharField()
year = serializers.ReadOnlyField()
class Meta:
model = Year
fields = ("id", "name", "year")
class AdvisorSerializer(
ClubRouteMixin, ManyToManySaveMixin, serializers.ModelSerializer
):
class Meta:
model = Advisor
fields = ("id", "name", "title", "department", "email", "phone", "public")
class ClubEventSerializer(serializers.ModelSerializer):
"""
Within the context of an existing club, return events that are a part of this club.
"""
image = serializers.ImageField(write_only=True, required=False, allow_null=True)
image_url = serializers.SerializerMethodField("get_image_url")
large_image_url = serializers.SerializerMethodField("get_large_image_url")
url = serializers.SerializerMethodField("get_event_url")
creator = serializers.HiddenField(default=serializers.CurrentUserDefault())
def get_event_url(self, obj):
# if no url, return that
if not obj.url:
return obj.url
# if is zoom link, hide url unless authenticated
if "request" in self.context and "zoom.us" in urlparse(obj.url).netloc:
user = self.context["request"].user
if user.is_authenticated:
return obj.url
return "(Login to view url)"
return obj.url
def get_large_image_url(self, obj):
image = obj.image
# correct path rendering
if not image:
return None
if image.url.startswith("http"):
return image.url
elif "request" in self.context:
return self.context["request"].build_absolute_uri(image.url)
else:
return image.url
def get_image_url(self, obj):
# use thumbnail if exists
image = obj.image_small
if not image:
image = obj.image
# fix image path in development
if not image:
return None
if image.url.startswith("http"):
return image.url
elif "request" in self.context:
return self.context["request"].build_absolute_uri(image.url)
else:
return image.url
def validate_url(self, value):
"""
Ensure that the URL is valid.
"""
# convert none to blank
if value is None:
value = ""
# remove surrounding whitespace
value = value.strip()
# throw an error if the url is not valid
if value:
validate = URLValidator()
try:
validate(value)
except DjangoValidationError:
raise serializers.ValidationError(
"The URL you entered does not appear to be valid. "
"Please check your URL and try again."
)
# expand links copied from google calendar
if value:
parsed = urlparse(value)
if parsed.netloc.endswith(".google.com") and parsed.path == "/url":
return parse_qs(parsed.query)["q"][0]
return value
def validate_description(self, value):
"""
Allow the description to have HTML tags that come from a whitelist.
"""
return clean(bleach.linkify(value))
def validate(self, data):
start_time = data.get(
"start_time",
self.instance.start_time if self.instance is not None else None,
)
end_time = data.get(
"end_time", self.instance.end_time if self.instance is not None else None
)
if start_time is not None and end_time is not None and start_time > end_time:
raise serializers.ValidationError(
"Your event start time must be less than the end time!"
)
return data
def update(self, instance, validated_data):
# ensure user cannot update start time or end time for a fair event
user = self.context["request"].user
if not (user.is_authenticated and user.has_perm("clubs.see_fair_status")):
if instance and instance.type == Event.FAIR:
unchanged_fields = {"start_time", "end_time"}
for field in unchanged_fields:
if (
field in validated_data
and not getattr(self.instance, field, None)
== validated_data[field]
):
raise serializers.ValidationError(
"You cannot change the meeting time for a fair event! "
"If you would like to, please contact the fair organizers."
)
return super().update(instance, validated_data)
def save(self):
if "club" not in self.validated_data:
self.validated_data["club"] = Club.objects.get(
code=self.context["view"].kwargs.get("club_code")
)
if not self.validated_data.get("code") and self.validated_data.get("name"):
self.validated_data["code"] = slugify(self.validated_data["name"])
return super().save()
class Meta:
model = Event
fields = [
"creator",
"description",
"end_time",
"id",
"image",
"image_url",
"is_ics_event",
"large_image_url",
"location",
"name",
"start_time",
"type",
"url",
]
class EventSerializer(ClubEventSerializer):
"""
A serializer for an event that includes basic associated club information.
"""
club = serializers.SlugRelatedField(
queryset=Club.objects.all(), required=False, slug_field="code"
)
club_name = serializers.SerializerMethodField()
badges = BadgeSerializer(source="club.badges", many=True, read_only=True)
pinned = serializers.BooleanField(read_only=True)
def get_club_name(self, obj):
if obj.club is None:
return None
return obj.club.name
class Meta:
model = Event
fields = ClubEventSerializer.Meta.fields + [
"club",
"club_name",
"badges",
"pinned",
]
class EventWriteSerializer(EventSerializer):
"""
A serializer for an event that is used when creating/editing the event.
Enables URL checking for the url field.
"""
url = serializers.CharField(
max_length=2048, required=False, allow_blank=True, allow_null=True
)
def update(self, instance, validated_data):
"""
Enforce only changing the meeting link to Zoom links for activities fair events.
"""
if instance.type == Event.FAIR and "url" in validated_data:
old_url = instance.url or ""
new_url = validated_data.get("url", "")
# if the two urls are not equal, perform additional checks
if old_url != new_url:
parsed_url = urlparse(new_url)
if ".zoom.us" not in parsed_url.netloc and new_url:
raise serializers.ValidationError(
{
"url": "You should use a Zoom link for the meeting url! "
"You can use the Zoom setup page to do this for you."
}
)
return super().update(instance, validated_data)
class MembershipInviteSerializer(serializers.ModelSerializer):
id = serializers.CharField(max_length=8, read_only=True)
email = serializers.EmailField(read_only=True)
token = serializers.CharField(max_length=128, write_only=True)
name = serializers.CharField(source="club.name", read_only=True)
public = serializers.BooleanField(write_only=True, required=False)
def create(self, validated_data):
validated_data.pop("public", None)
return super().create(validated_data)
def update(self, instance, validated_data):
user = self.context["request"].user
public = validated_data.pop("public", False)
if not self.validated_data.get("token") == self.instance.token:
raise serializers.ValidationError("Missing or invalid token in request!")
# if there is an owner and the invite is for a upenn email,
# do strict username checking
if (
self.instance.email.endswith((".upenn.edu", "@upenn.edu"))
and self.instance.club.membership_set.count() > 0
):
# penn medicine emails have multiple aliases
if not self.instance.email.endswith("@pennmedicine.upenn.edu"):
invite_username = self.instance.email.rsplit("@", 1)[0]
if not (
invite_username.lower() == user.username.lower()
or self.instance.email == user.email
):
raise serializers.ValidationError(
f"This invitation was meant for {invite_username}, "
f"but you are logged in as {user.username}!"
)
# claim the invite and set the membership public status
obj = instance.claim(user)
obj.public = public
obj.save()
# if a membership request exists, delete it
MembershipRequest.objects.filter(person=user, club=self.instance.club).delete()
return instance
class Meta:
model = MembershipInvite
fields = [
"email",
"id",
"name",
"public",
"role",
"title",
"token",
"updated_at",
]
class ExternalMemberListSerializer(serializers.ModelSerializer):
"""
This serializer is used for listing non-sensitive data
accessible to the public via CORS
"""
name = serializers.CharField(source="person.username")
image = serializers.SerializerMethodField("get_image")
def get_image(self, obj):
if not obj.image and not obj.person.profile.image:
return None
return obj.image.url if obj.image else obj.person.profile.image.url
class Meta:
model = Membership
fields = ["name", "role", "description", "image"]
class UserMembershipInviteSerializer(MembershipInviteSerializer):
"""
This serializer is used for listing the email invitations
that the current user was sent.
"""
token = serializers.CharField(max_length=128)
code = serializers.CharField(source="club.code", read_only=True)
class Meta(MembershipInviteSerializer.Meta):
fields = MembershipInviteSerializer.Meta.fields + ["code"]
class MembershipSerializer(ClubRouteMixin, serializers.ModelSerializer):
"""
Used for listing which users are in a club for members who are not in the club.
"""
email = serializers.SerializerMethodField("get_email")
username = serializers.SerializerMethodField("get_username")
name = serializers.SerializerMethodField("get_full_name")
person = serializers.PrimaryKeyRelatedField(
queryset=get_user_model().objects.all(), write_only=True
)
role = serializers.IntegerField(write_only=True, required=False)
image = serializers.SerializerMethodField("get_image")
def get_username(self, obj):
if not obj.public:
return None
return obj.person.username
def get_full_name(self, obj):
if not obj.public:
return "Anonymous"
return obj.person.get_full_name()
def get_email(self, obj):
if not obj.public or not obj.person.profile.show_profile:
return None
return obj.person.email
def get_image(self, obj):
if not obj.public:
return None
if not obj.image and not obj.person.profile.image:
return None
image_url = obj.image.url if obj.image else obj.person.profile.image.url
if image_url.startswith("http"):
return image_url
elif "request" in self.context:
return self.context["request"].build_absolute_uri(image_url)
else:
return image_url
def validate_role(self, value):
"""
Ensure that users cannot promote themselves to a higher role.
Also ensure that owners can't demote themselves without leaving another owner.
"""
user = self.context["request"].user
mem_user_id = (
self.instance.person.id if self.instance else self.initial_data["person"]
)
club_code = self.context["view"].kwargs.get(
"club_code", self.context["view"].kwargs.get("code")
)
membership = Membership.objects.filter(
person=user, club__code=club_code
).first()
if user.has_perm("clubs.manage_club"):
return value
if membership is None:
raise serializers.ValidationError(
"You must be a member of this club to modify roles!"
)
if membership.role > value:
raise serializers.ValidationError(
"You cannot promote someone above your own level."
)
if value > Membership.ROLE_OWNER and user.id == mem_user_id:
if membership.role <= Membership.ROLE_OWNER:
if (
Membership.objects.filter(
club__code=club_code, role__lte=Membership.ROLE_OWNER
).count()
<= 1
):
raise serializers.ValidationError(
"You cannot demote yourself if you are the only owner!"
)
return value
def validate(self, data):
"""
Normal members can only change a small subset of information.
"""
user = self.context["request"].user
club_code = self.context["view"].kwargs.get(
"club_code", self.context["view"].kwargs.get("code")
)
membership = Membership.objects.filter(
person=user, club__code=club_code
).first()
if not user.is_superuser and (
membership is None or membership.role > Membership.ROLE_OFFICER
):
for field in data:
if field not in {"active", "public"}:
raise serializers.ValidationError(
'Normal members are not allowed to change "{}"!'.format(field)
)
return data
class Meta:
model = Membership
fields = [
"active",
"email",
"image",
"name",
"person",
"public",
"role",
"title",
"username",
"description",
]
class AuthenticatedMembershipSerializer(MembershipSerializer):
"""
Provides additional information about members, such as email address.
Should only be available to users in the club.
"""
role = serializers.IntegerField(required=False)
email = serializers.EmailField(source="person.email", read_only=True)
username = serializers.CharField(source="person.username", read_only=True)
def get_full_name(self, obj):
return obj.person.get_full_name()
class Meta(MembershipSerializer.Meta):
pass
class ClubMinimalSerializer(serializers.ModelSerializer):
"""
Return only the club name, code, and approval status for a club.
"""
class Meta:
model = Club
fields = ["name", "code", "approved"]
class ClubConstitutionSerializer(ClubMinimalSerializer):
"""
Return the minimal information, as well as the files that the club has uploaded.
"""
files = serializers.SerializerMethodField("get_constitution")
def get_constitution(self, obj):
user = self.context["request"].user
perm = user.is_authenticated and user.has_perm("clubs.see_pending_clubs")
if hasattr(obj, "user_membership_set"):
has_member = bool(obj.user_membership_set)
else:
has_member = False
if hasattr(obj, "prefetch_asset_set"):
return [
{
"name": asset.name if perm or has_member else None,
"url": asset.file.url if perm or has_member else None,
}
for asset in obj.prefetch_asset_set
if asset.name.endswith((".docx", ".doc", ".pdf"))
or "constitution" in asset.name.lower()
]
return None
class Meta(ClubMinimalSerializer.Meta):
fields = ClubMinimalSerializer.Meta.fields + ["files"]
class ClubListSerializer(serializers.ModelSerializer):
"""
The club list serializer returns a subset of the information that the full
serializer returns.
Optimized for the home page, some fields may be missing if not necessary.
For example, if the subtitle is set, the description is returned as null.
This is done for a quicker response.
"""
tags = TagSerializer(many=True)
image_url = serializers.SerializerMethodField("get_image_url")
favorite_count = serializers.IntegerField(read_only=True)
membership_count = serializers.IntegerField(read_only=True)
is_favorite = serializers.SerializerMethodField("get_is_favorite")
is_subscribe = serializers.SerializerMethodField("get_is_subscribe")
is_member = serializers.SerializerMethodField("get_is_member")
email = serializers.SerializerMethodField("get_email")
subtitle = serializers.SerializerMethodField("get_short_description")
def get_email(self, obj):
if obj.email_public:
return obj.email
return "Hidden"
def get_short_description(self, obj):
if obj.subtitle:
return obj.subtitle
# return first sentence of description without html tags
desc = obj.description.lstrip()[:1000]
cleaned_desc = re.sub(r"<[^>]+>", "", desc)
return (
"".join(re.split(r"(\.|\n|!)", cleaned_desc)[:2])
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("–", "-")
.replace("—", "-")
.replace(" ", " ")
.strip()
)
def get_is_favorite(self, obj):
user = self.context["request"].user
if not user.is_authenticated:
return False
if hasattr(obj, "user_favorite_set"):
return bool(obj.user_favorite_set)
return obj.favorite_set.filter(person=user).exists()
def get_is_subscribe(self, obj):
user = self.context["request"].user
if not user.is_authenticated:
return False
if hasattr(obj, "user_subscribe_set"):
return bool(obj.user_subscribe_set)
return obj.subscribe_set.filter(person=user).exists()
def get_is_member(self, obj):
user = self.context["request"].user
if not user.is_authenticated:
return False
if hasattr(obj, "user_membership_set"):
mship = next(iter(obj.user_membership_set), None)
else:
mship = obj.membership_set.filter(person=user).first()
if mship is None:
return False
return mship.role
def get_image_url(self, obj):
# use small version if exists
image = obj.image_small
if not image:
image = obj.image
# correct path rendering
if not image:
return None
if image.url.startswith("http"):
return image.url
elif "request" in self.context:
return self.context["request"].build_absolute_uri(image.url)
else:
return image.url
def get_fields(self):
"""
Override the fields that are returned if the "fields" GET parameter
is specified. Acts as a filter on the returned fields.
"""
all_fields = super().get_fields()
# add in additional report fields
if hasattr(self.__class__, "get_additional_fields"):
for fields in self.__class__.get_additional_fields().values():
for field in fields.values():
all_fields[field] = ReportClubField(field, read_only=True)
fields_param = getattr(self.context.get("request", dict()), "GET", {}).get(
"fields", ""
)
if fields_param:
fields_param = fields_param.split(",")
else:
return all_fields
fields_subset = dict()
for k in fields_param:
if k in all_fields:
fields_subset[k] = all_fields[k]
return fields_subset if len(fields_subset) > 0 else all_fields
def to_representation(self, instance):
"""
Return the previous approved version of a club for users
that should not see unapproved content.
"""
if instance.ghost and not instance.approved:
user = self.context["request"].user
can_see_pending = user.has_perm("clubs.see_pending_clubs") or user.has_perm(
"clubs.manage_club"
)
is_member = (
user.is_authenticated
and instance.membership_set.filter(person=user).exists()
)
if not can_see_pending and not is_member:
historical_club = (
instance.history.filter(approved=True)
.order_by("-approved_on")
.first()
)
if historical_club is not None:
approved_instance = historical_club.instance
approved_instance._is_historical = True
return super().to_representation(approved_instance)
return super().to_representation(instance)
class Meta:
model = Club
fields = [
"accepting_members",
"active",
"address",
"application_required",
"appointment_needed",
"approved",
"available_virtually",
"code",
"email",
"enables_subscription",
"favorite_count",
"founded",
"image_url",
"is_favorite",
"is_member",
"is_subscribe",
"membership_count",
"recruiting_cycle",
"name",
"size",
"subtitle",
"tags",
]
extra_kwargs = {
"name": {
"validators": [validators.UniqueValidator(queryset=Club.objects.all())],
"help_text": "The name of the club.",
},
"code": {
"required": False,
"validators": [validators.UniqueValidator(queryset=Club.objects.all())],
"help_text": "An alphanumeric string shown in the URL "
"and used to identify this club.",
},
"description": {
"help_text": "A long description for the club. "
"Certain HTML tags are allowed."
},
"email": {"help_text": "The primary contact email for the club."},
"subtitle": {
"required": False,
"help_text": "The text shown to the user in a preview card. "
"Short description of the club.",
},
}
class MembershipClubListSerializer(ClubListSerializer):
"""
The club list serializer, except return more detailed information about the
relationship of the club with the authenticated user.
Used on the user profile page to show additional information.
"""
membership = serializers.SerializerMethodField("get_membership")
def get_membership(self, obj):
mship = obj.profile_membership_set[0]
return {
"active": mship.active,
"title": mship.title,
"role": mship.role,
}
def get_is_member(self, obj):