-
-
Notifications
You must be signed in to change notification settings - Fork 672
Expand file tree
/
Copy pathforms.py
More file actions
890 lines (746 loc) · 34.5 KB
/
forms.py
File metadata and controls
890 lines (746 loc) · 34.5 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
"""Forms for the sponsors app sponsorship application and admin workflows."""
import datetime
from itertools import chain
from django import forms
from django.conf import settings
from django.contrib.admin.widgets import AdminDateWidget
from django.core.validators import FileExtensionValidator
from django.db.models import Q
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.html import format_html
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django_countries.fields import CountryField
from apps.sponsors.models import (
SPONSOR_TEMPLATE_HELP_TEXT,
BenefitFeature,
RequiredImgAssetConfiguration,
Sponsor,
SponsorBenefit,
SponsorContact,
SponsorEmailNotificationTemplate,
Sponsorship,
SponsorshipBenefit,
SponsorshipCurrentYear,
SponsorshipPackage,
SponsorshipProgram,
)
SPONSORSHIP_YEAR_SELECT = forms.Select(
choices=(((None, "---"), *tuple((y, str(y)) for y in range(2021, timezone.now().date().year + 2))))
)
class PickSponsorshipBenefitsField(forms.ModelMultipleChoiceField):
"""Multi-select field for choosing sponsorship benefits with checkbox widget."""
widget = forms.CheckboxSelectMultiple
def label_from_instance(self, obj):
"""Return the benefit name as the display label."""
return obj.name
class SponsorContactForm(forms.ModelForm):
"""Form for entering sponsor contact information."""
class Meta:
"""Meta configuration for SponsorContactForm."""
model = SponsorContact
fields = ["name", "email", "phone", "primary", "administrative", "accounting"]
SponsorContactFormSet = forms.formset_factory(
SponsorContactForm,
extra=0,
min_num=1,
validate_min=True,
can_delete=False,
can_order=False,
max_num=5,
)
class SponsorshipsBenefitsForm(forms.Form):
"""Form to select packages, benefits, and a la carte during sponsorship application.
Enable user to select packages, benefits and a la carte during
the sponsorship application submission.
"""
def __init__(self, *args, **kwargs):
"""Initialize form with dynamic benefit and package fields for the given year."""
year = kwargs.pop("year", SponsorshipCurrentYear.get_year())
super().__init__(*args, **kwargs)
self.fields["package"] = forms.ModelChoiceField(
queryset=SponsorshipPackage.objects.from_year(year).list_advertisables(),
widget=forms.RadioSelect(),
required=False,
empty_label=None,
)
self.fields["a_la_carte_benefits"] = PickSponsorshipBenefitsField(
required=False,
queryset=SponsorshipBenefit.objects.from_year(year).a_la_carte().select_related("program"),
)
self.fields["standalone_benefits"] = PickSponsorshipBenefitsField(
required=False,
queryset=SponsorshipBenefit.objects.from_year(year).standalone().select_related("program"),
)
benefits_qs = SponsorshipBenefit.objects.from_year(year).with_packages().select_related("program")
for program in SponsorshipProgram.objects.all():
slug = slugify(program.name).replace("-", "_")
self.fields[f"benefits_{slug}"] = PickSponsorshipBenefitsField(
queryset=benefits_qs.filter(program=program),
required=False,
label=_("{program_name} Benefits").format(program_name=program.name),
)
@property
def benefits_programs(self):
"""Return form fields that correspond to program-specific benefits."""
return [f for f in self if f.name.startswith("benefits_")]
@property
def benefits_conflicts(self):
"""Returns a dict with benefits ids as keys and their list of conlicts ids as values."""
conflicts = {}
for benefit in SponsorshipBenefit.objects.with_conflicts():
benefits_conflicts = benefit.conflicts.values_list("id", flat=True)
if benefits_conflicts:
conflicts[benefit.id] = list(benefits_conflicts)
return conflicts
def get_benefits(self, cleaned_data=None, include_a_la_carte=False, include_standalone=False):
"""Collect and return the selected benefits from all program fields."""
cleaned_data = cleaned_data or self.cleaned_data
benefits = list(chain(*(cleaned_data.get(bp.name) for bp in self.benefits_programs)))
a_la_carte = cleaned_data.get("a_la_carte_benefits", [])
if include_a_la_carte:
benefits.extend(list(a_la_carte))
standalone = cleaned_data.get("standalone_benefits", [])
if include_standalone:
benefits.extend(list(standalone))
return benefits
def get_package(self):
"""Return the selected package or create a standalone-only package if needed."""
pkg = self.cleaned_data.get("package")
pkg_benefits = self.get_benefits(include_a_la_carte=True)
standalone = self.cleaned_data.get("standalone_benefits")
if not pkg_benefits and standalone: # standalone only
pkg, _ = SponsorshipPackage.objects.get_or_create(
slug="standalone-only",
year=SponsorshipCurrentYear.get_year(),
defaults={"name": "Standalone Only", "sponsorship_amount": 0},
)
return pkg
def _clean_benefits(self, cleaned_data): # noqa: C901 - benefit validation has inherent complexity
"""Validate chosen benefits.
Invalid scenarios are:
- benefits with conflits
- package only benefits and form without SponsorshipProgram
- benefit with no capacity, except if soft.
"""
package = cleaned_data.get("package")
benefits = self.get_benefits(cleaned_data, include_a_la_carte=True)
a_la_carte = cleaned_data.get("a_la_carte_benefits")
standalone = cleaned_data.get("standalone_benefits")
if not benefits and not standalone:
raise forms.ValidationError(_("You have to pick a minimum number of benefits."))
if benefits and not package:
raise forms.ValidationError(_("You must pick a package to include the selected benefits."))
if standalone and package:
raise forms.ValidationError(_("Application with package cannot have standalone benefits."))
if package and a_la_carte and not package.allow_a_la_carte:
raise forms.ValidationError(_("Package does not accept a la carte benefits."))
benefits_ids = [b.id for b in benefits]
for benefit in benefits:
conflicts = set(self.benefits_conflicts.get(benefit.id, []))
if conflicts and set(benefits_ids).intersection(conflicts):
raise forms.ValidationError(_("The application has 1 or more benefits that conflicts."))
if benefit.package_only:
if not package:
raise forms.ValidationError(
_("The application has 1 or more package only benefits and no sponsor package.")
)
if not benefit.packages.filter(id=package.id).exists():
raise forms.ValidationError(
_("The application has 1 or more package only benefits but wrong sponsor package.")
)
if not benefit.has_capacity:
raise forms.ValidationError(_("The application has 1 or more benefits with no capacity."))
return cleaned_data
def clean(self):
"""Validate the form by checking benefit selections and conflicts."""
cleaned_data = super().clean()
return self._clean_benefits(cleaned_data)
class SponsorshipApplicationForm(forms.Form):
"""Form for submitting a new sponsorship application with sponsor details."""
name = forms.CharField(
max_length=100,
label="Sponsor name",
help_text="Name of the sponsor, for public display.",
required=False,
)
description = forms.CharField(
label="Sponsor description",
help_text="Brief description of the sponsor for public display.",
required=False,
widget=forms.TextInput,
)
landing_page_url = forms.URLField(
label="Sponsor landing page",
help_text="Landing page URL. The linked page may not contain any sales or marketing information.",
required=False,
)
twitter_handle = forms.CharField(
max_length=32,
label="Twitter handle",
help_text="For promotion of your sponsorship on social media.",
required=False,
)
linked_in_page_url = forms.URLField(
label="LinkedIn page URL",
help_text="URL for your LinkedIn page.",
required=False,
)
web_logo = forms.ImageField(
label="Sponsor web logo",
help_text="For display on our sponsor webpage. High resolution PNG or JPG, smallest dimension no less than 256px",
required=False,
)
white_logo = forms.ImageField(
label="Sponsor white logo",
help_text="For display on dark backgrounds (e.g. PyPI footer). Transparent PNG, smallest dimension no less than 256px",
required=False,
)
print_logo = forms.FileField(
label="Sponsor print logo",
help_text="For printed materials, signage, and projection. SVG or EPS",
required=False,
validators=[FileExtensionValidator(["eps", "epsfepsi", "svg", "png"])],
)
primary_phone = forms.CharField(
label="Sponsor Primary Phone",
max_length=32,
required=False,
)
mailing_address_line_1 = forms.CharField(
label="Mailing Address line 1",
widget=forms.TextInput,
required=False,
)
mailing_address_line_2 = forms.CharField(
label="Mailing Address line 2",
widget=forms.TextInput,
required=False,
)
city = forms.CharField(max_length=64, required=False)
state = forms.CharField(label="State/Province/Region", max_length=64, required=False)
state_of_incorporation = forms.CharField(
label="State of incorporation",
help_text="US only, If different than mailing address",
max_length=64,
required=False,
)
postal_code = forms.CharField(label="Zip/Postal Code", max_length=64, required=False)
country = CountryField().formfield(required=False, help_text="For mailing/contact purposes")
country_of_incorporation = CountryField().formfield(
label="Country of incorporation", help_text="For contractual purposes", required=False
)
def __init__(self, *args, **kwargs):
"""Initialize form with user context and contact formset."""
self.user = kwargs.pop("user", None)
super().__init__(*args, **kwargs)
qs = Sponsor.objects.none()
if self.user:
sponsor_ids = SponsorContact.objects.filter(user=self.user).values_list("sponsor", flat=True)
qs = Sponsor.objects.filter(id__in=sponsor_ids)
self.fields["sponsor"] = forms.ModelChoiceField(queryset=qs, required=False)
formset_kwargs = {"prefix": "contact"}
if self.data:
self.contacts_formset = SponsorContactFormSet(self.data, **formset_kwargs)
else:
self.contacts_formset = SponsorContactFormSet(initial=[{"primary": True}], **formset_kwargs)
def clean(self):
"""Validate contacts formset and ensure a primary contact exists."""
super().clean()
sponsor = self.data.get("sponsor")
if not sponsor and not self.contacts_formset.is_valid():
msg = "Errors with contact(s) information"
if not self.contacts_formset.errors:
msg = "You have to enter at least one contact"
raise forms.ValidationError(msg)
if not sponsor:
has_primary_contact = any(f.cleaned_data.get("primary") for f in self.contacts_formset.forms)
if not has_primary_contact:
msg = "You have to mark at least one contact as the primary one."
raise forms.ValidationError(msg)
def clean_sponsor(self):
"""Validate that the selected sponsor has no open sponsorship applications."""
sponsor = self.cleaned_data.get("sponsor")
if not sponsor:
return None
if Sponsorship.objects.in_progress().filter(sponsor=sponsor).exists():
msg = f"The sponsor {sponsor.name} already have open Sponsorship applications. "
msg += f"Get in contact with {settings.SPONSORSHIP_NOTIFICATION_FROM_EMAIL} to discuss."
raise forms.ValidationError(msg)
return sponsor
# Required fields are being manually validated because if the form
# data has a Sponsor they shouldn't be required
def clean_name(self):
"""Validate and clean the sponsor name field when no existing sponsor is selected."""
name = self.cleaned_data.get("name", "")
sponsor = self.data.get("sponsor")
if not sponsor and not name:
msg = "This field is required."
raise forms.ValidationError(msg)
return name.strip()
def clean_web_logo(self):
"""Validate that a web logo is provided when no existing sponsor is selected."""
web_logo = self.cleaned_data.get("web_logo", "")
sponsor = self.data.get("sponsor")
if not sponsor and not web_logo:
msg = "This field is required."
raise forms.ValidationError(msg)
return web_logo
def clean_primary_phone(self):
"""Validate that a phone number is provided when no existing sponsor is selected."""
primary_phone = self.cleaned_data.get("primary_phone", "")
sponsor = self.data.get("sponsor")
if not sponsor and not primary_phone:
msg = "This field is required."
raise forms.ValidationError(msg)
return primary_phone.strip()
def clean_mailing_address_line_1(self):
"""Validate that a mailing address is provided when no existing sponsor is selected."""
mailing_address_line_1 = self.cleaned_data.get("mailing_address_line_1", "")
sponsor = self.data.get("sponsor")
if not sponsor and not mailing_address_line_1:
msg = "This field is required."
raise forms.ValidationError(msg)
return mailing_address_line_1.strip()
def clean_city(self):
"""Validate that a city is provided when no existing sponsor is selected."""
city = self.cleaned_data.get("city", "")
sponsor = self.data.get("sponsor")
if not sponsor and not city:
msg = "This field is required."
raise forms.ValidationError(msg)
return city.strip()
def clean_postal_code(self):
"""Validate that a postal code is provided when no existing sponsor is selected."""
postal_code = self.cleaned_data.get("postal_code", "")
sponsor = self.data.get("sponsor")
if not sponsor and not postal_code:
msg = "This field is required."
raise forms.ValidationError(msg)
return postal_code.strip()
def clean_country(self):
"""Validate that a country is provided when no existing sponsor is selected."""
country = self.cleaned_data.get("country", "")
sponsor = self.data.get("sponsor")
if not sponsor and not country:
msg = "This field is required."
raise forms.ValidationError(msg)
return country.strip()
def save(self):
"""Create a new Sponsor with contacts or return the selected existing sponsor."""
selected_sponsor = self.cleaned_data.get("sponsor")
if selected_sponsor:
return selected_sponsor
sponsor = Sponsor.objects.create(
name=self.cleaned_data["name"],
web_logo=self.cleaned_data["web_logo"],
primary_phone=self.cleaned_data["primary_phone"],
mailing_address_line_1=self.cleaned_data["mailing_address_line_1"],
mailing_address_line_2=self.cleaned_data.get("mailing_address_line_2", ""),
city=self.cleaned_data["city"],
state=self.cleaned_data.get("state", ""),
postal_code=self.cleaned_data["postal_code"],
country=self.cleaned_data["country"],
description=self.cleaned_data.get("description", ""),
landing_page_url=self.cleaned_data.get("landing_page_url", ""),
twitter_handle=self.cleaned_data["twitter_handle"],
linked_in_page_url=self.cleaned_data["linked_in_page_url"],
white_logo=self.cleaned_data.get("white_logo"),
print_logo=self.cleaned_data.get("print_logo"),
country_of_incorporation=self.cleaned_data.get("country_of_incorporation", ""),
state_of_incorporation=self.cleaned_data.get("state_of_incorporation", ""),
)
contacts = [f.save(commit=False) for f in self.contacts_formset.forms]
for contact in contacts:
if self.user and self.user.email.lower() == contact.email.lower():
contact.user = self.user
contact.sponsor = sponsor
contact.save()
return sponsor
@cached_property
def user_with_previous_sponsors(self):
"""Return True if the user has previously associated sponsors."""
if not self.user:
return False
return self.fields["sponsor"].queryset.exists()
class SponsorshipReviewAdminForm(forms.ModelForm):
"""Admin form for reviewing and approving sponsorship applications."""
start_date = forms.DateField(widget=AdminDateWidget(), required=False)
end_date = forms.DateField(widget=AdminDateWidget(), required=False)
overlapped_by = forms.ModelChoiceField(
queryset=Sponsorship.objects.select_related("sponsor", "package"), required=False
)
renewal = forms.BooleanField(
help_text="If true, it means the sponsorship is a renewal of a previous sponsorship and will use the renewal template for contracting.",
required=False,
)
def __init__(self, *args, **kwargs):
"""Initialize form with optional forced required fields and overlapped filtering."""
force_required = kwargs.pop("force_required", False)
super().__init__(*args, **kwargs)
if self.instance:
qs = self.fields["overlapped_by"].queryset.exclude(id=self.instance.id)
self.fields["overlapped_by"].queryset = qs.filter(sponsor_id=self.instance.sponsor_id)
if force_required:
self.fields.pop("overlapped_by") # overlapped should never be displayed on approval
for field_name in self.fields:
self.fields[field_name].required = True
self.fields["renewal"].required = False
class Meta:
"""Meta configuration for SponsorshipReviewAdminForm."""
model = Sponsorship
fields = ["start_date", "end_date", "package", "sponsorship_fee", "renewal"]
widgets = {
"year": SPONSORSHIP_YEAR_SELECT,
}
def clean(self):
"""Validate that the end date is after the start date."""
cleaned_data = super().clean()
start_date = cleaned_data.get("start_date")
end_date = cleaned_data.get("end_date")
if start_date and end_date and end_date <= start_date:
msg = "End date must be greater than start date"
raise forms.ValidationError(msg)
return cleaned_data
class SignedSponsorshipReviewAdminForm(SponsorshipReviewAdminForm):
"""Form to approve sponsorships that already have a signed contract."""
signed_contract = forms.FileField(help_text="Please upload the final version of the signed contract.")
class SponsorBenefitAdminInlineForm(forms.ModelForm):
"""Inline form for managing individual sponsor benefits within a sponsorship."""
sponsorship_benefit = forms.ModelChoiceField(
queryset=SponsorshipBenefit.objects.order_by("program", "order").select_related("program"),
required=False,
)
def __init__(self, *args, **kwargs):
"""Initialize the inline form."""
super().__init__(*args, **kwargs)
class Meta:
"""Meta configuration for SponsorBenefitAdminInlineForm."""
model = SponsorBenefit
fields = ["sponsorship_benefit", "sponsorship", "benefit_internal_value"]
def save(self, commit=True):
"""Save the sponsor benefit, updating features when the benefit type changes."""
sponsorship = self.cleaned_data["sponsorship"]
benefit = self.cleaned_data["sponsorship_benefit"]
value = self.cleaned_data["benefit_internal_value"]
if not (self.instance and self.instance.pk): # new benefit
self.instance = SponsorBenefit(sponsorship=sponsorship)
else:
self.instance.refresh_from_db()
self.instance.benefit_internal_value = benefit.internal_value
if value:
self.instance.benefit_internal_value = value
updated_sponsorship_benefit = False
if benefit.pk != self.instance.sponsorship_benefit_id:
updated_sponsorship_benefit = True
self.instance.sponsorship_benefit = benefit
self.instance.name = benefit.name
self.instance.description = benefit.description
self.instance.program = benefit.program
self.instance.added_by_user = self.instance.added_by_user or benefit.standalone
self.instance.standalone = benefit.standalone
if commit:
self.instance.save()
if updated_sponsorship_benefit:
self.instance.features.all().delete()
for feature_config in benefit.features_config.all():
feature_config.create_benefit_feature(self.instance)
return self.instance
class SponsorshipsListForm(forms.Form):
"""Form for selecting multiple sponsorships via checkboxes."""
sponsorships = forms.ModelMultipleChoiceField(
required=True,
queryset=Sponsorship.objects.select_related("sponsor"),
widget=forms.CheckboxSelectMultiple,
)
@classmethod
def with_benefit(cls, sponsorship_benefit, *args, **kwargs):
"""Queryset considering only valid sponsorships which have the benefit."""
today = timezone.now().date()
queryset = sponsorship_benefit.related_sponsorships.exclude(
Q(end_date__lt=today) | Q(status=Sponsorship.REJECTED)
).select_related("sponsor")
form = cls(*args, **kwargs)
form.fields["sponsorships"].queryset = queryset
form.sponsorship_benefit = sponsorship_benefit
return form
class SendSponsorshipNotificationForm(forms.Form):
"""Form for sending email notifications to sponsorship contacts."""
contact_types = forms.MultipleChoiceField(
choices=SponsorContact.CONTACT_TYPES,
required=True,
widget=forms.CheckboxSelectMultiple,
)
notification = forms.ModelChoiceField(
queryset=SponsorEmailNotificationTemplate.objects.all(),
help_text="You can select an existing notification or your own custom subject/content",
required=False,
)
subject = forms.CharField(max_length=140, required=False)
content = forms.CharField(
widget=forms.widgets.Textarea(),
required=False,
help_text=SPONSOR_TEMPLATE_HELP_TEXT,
)
def clean(self):
"""Validate that either a notification template or custom content is provided, not both."""
cleaned_data = super().clean()
notification = cleaned_data.get("notification")
subject = cleaned_data.get("subject", "").strip()
content = cleaned_data.get("content", "").strip()
custom_notification = subject or content
if not (notification or custom_notification):
msg = "Can not send email without notification or custom content"
raise forms.ValidationError(msg)
if notification and custom_notification:
msg = "You must select a notification or use custom content, not both"
raise forms.ValidationError(msg)
return cleaned_data
def get_notification(self):
"""Return the selected template or a new template built from custom content."""
default_notification = SponsorEmailNotificationTemplate(
content=self.cleaned_data["content"],
subject=self.cleaned_data["subject"],
)
return self.cleaned_data.get("notification") or default_notification
class SponsorUpdateForm(forms.ModelForm):
"""Form for sponsors to update their own profile information."""
READONLY_FIELDS = [
"name",
]
web_logo = forms.ImageField(
widget=forms.widgets.FileInput,
help_text="For display on our sponsor webpage. High resolution PNG or JPG, smallest dimension no less than 256px",
required=False,
)
white_logo = forms.ImageField(
widget=forms.widgets.FileInput,
help_text="For display on dark backgrounds (e.g. PyPI footer). Transparent PNG, smallest dimension no less than 256px",
required=False,
)
print_logo = forms.FileField(
widget=forms.widgets.FileInput,
help_text="For printed materials, signage, and projection. SVG or EPS",
required=False,
validators=[FileExtensionValidator(["eps", "epsfepsi", "svg", "png"])],
)
def __init__(self, *args, **kwargs):
"""Initialize form with inline contact formset and readonly field configuration."""
super().__init__(*args, **kwargs)
formset_kwargs = {"prefix": "contact", "instance": self.instance}
factory = forms.inlineformset_factory(
Sponsor,
SponsorContact,
form=SponsorContactForm,
extra=0,
min_num=1,
validate_min=True,
can_delete=True,
can_order=False,
max_num=5,
)
if self.data:
self.contacts_formset = factory(self.data, **formset_kwargs)
else:
self.contacts_formset = factory(**formset_kwargs)
# display fields as read-only
for disabled in self.READONLY_FIELDS:
self.fields[disabled].widget.attrs["readonly"] = True
class Meta:
"""Meta configuration for SponsorUpdateForm."""
model = Sponsor
fields = [
"name",
"description",
"landing_page_url",
"twitter_handle",
"linked_in_page_url",
"web_logo",
"white_logo",
"print_logo",
"primary_phone",
"mailing_address_line_1",
"mailing_address_line_2",
"city",
"state",
"postal_code",
"country",
"country_of_incorporation",
"state_of_incorporation",
]
def clean(self):
"""Validate the contacts formset and ensure a primary contact is designated."""
super().clean()
if not self.contacts_formset.is_valid():
msg = "Errors with contact(s) information"
if not self.contacts_formset.errors:
msg = "You have to enter at least one contact"
raise forms.ValidationError(msg)
has_primary_contact = any(f.cleaned_data.get("primary") for f in self.contacts_formset.forms)
if not has_primary_contact:
msg = "You have to mark at least one contact as the primary one."
raise forms.ValidationError(msg)
def save(self, *args, **kwargs):
"""Save the sponsor model and associated contact formset."""
super().save(*args, **kwargs)
self.contacts_formset.save()
class RequiredImgAssetConfigurationForm(forms.ModelForm):
"""Form for configuring required image asset constraints."""
def clean(self):
"""Validate that max dimensions are greater than min dimensions."""
data = super().clean()
min_width, max_width = data.get("min_width"), data.get("max_width")
if min_width and max_width and max_width < min_width:
msg = "Max width must be greater than min width"
raise forms.ValidationError(msg)
min_height, max_height = data.get("min_height"), data.get("max_height")
if min_height and max_height and max_height < min_height:
msg = "Max height must be greater than min height"
raise forms.ValidationError(msg)
return data
class Meta:
"""Meta configuration for RequiredImgAssetConfigurationForm."""
model = RequiredImgAssetConfiguration
fields = [
"benefit",
"related_to",
"internal_name",
"label",
"help_text",
"due_date",
"min_width",
"max_width",
"min_height",
"max_height",
]
class SponsorRequiredAssetsForm(forms.Form):
"""Form for sponsors to fulfill required asset information.
Built dynamically by fetching the required assets from the sponsorship.
"""
def __init__(self, *args, **kwargs):
"""Introspect the sponsorship object and build the form fields.
Dynamically generate form fields from the sponsorship's required assets.
"""
self.sponsorship = kwargs.pop("instance", None)
required_assets_ids = kwargs.pop("required_assets_ids", [])
if not self.sponsorship:
msg = "Form must be initialized with a sponsorship passed by the instance parameter"
raise TypeError(msg)
super().__init__(*args, **kwargs)
self.required_assets = BenefitFeature.objects.required_assets().from_sponsorship(self.sponsorship)
if required_assets_ids:
self.required_assets = self.required_assets.filter(pk__in=required_assets_ids)
fields = {}
ordered_assets = sorted(
self.required_assets,
key=lambda x: (-int(bool(x.value)), x.due_date or datetime.date.min),
reverse=True,
)
for required_asset in ordered_assets:
value = required_asset.value
f_name = self._get_field_name(required_asset)
required = bool(value)
field = required_asset.as_form_field(required=required, initial=value)
if required_asset.due_date and not bool(value):
field.label = format_html(
"<big><b>{}</b></big><br><b>(Required by {})</b>", field.label, required_asset.due_date
)
if bool(value):
field.label = format_html("<big><b>{}</b></big><br><small>(Fulfilled, thank you!)</small>", field.label)
fields[f_name] = field
self.fields.update(fields)
def _get_field_name(self, asset):
return slugify(asset.internal_name).replace("-", "_")
def update_assets(self):
"""Update every required asset with its value from the form data.
Iterate over every required asset, get the value from form data and
update it.
"""
for req_asset in self.required_assets:
f_name = self._get_field_name(req_asset)
value = self.cleaned_data.get(f_name, None)
if value is None:
continue
req_asset.value = value
@property
def has_input(self):
"""Return True if the form has any dynamically generated fields."""
return bool(self.fields)
class SponsorshipBenefitAdminForm(forms.ModelForm):
"""Admin form for editing sponsorship benefit configurations."""
class Meta:
"""Meta configuration for SponsorshipBenefitAdminForm."""
model = SponsorshipBenefit
widgets = {
"year": SPONSORSHIP_YEAR_SELECT,
}
fields = [
"name",
"description",
"program",
"packages",
"package_only",
"new",
"unavailable",
"standalone",
"legal_clauses",
"internal_description",
"internal_value",
"capacity",
"soft_capacity",
"conflicts",
"year",
]
def clean(self):
"""Validate that standalone benefits are not assigned to any package."""
cleaned_data = super().clean()
standalone = cleaned_data.get("standalone")
packages = cleaned_data.get("packages")
# standalone benefit cannot be associated with a package
if standalone and packages:
error = "Standalone benefits must not belong to any package."
raise forms.ValidationError(error)
return cleaned_data
class CloneApplicationConfigForm(forms.Form):
"""Form for cloning sponsorship application configuration from one year to another."""
from_year = forms.ChoiceField(
required=True, help_text="From which year you want to clone the benefits and packages.", choices=[]
)
target_year = forms.IntegerField(
required=True, help_text="The year of the resulting new sponsorship application configuration."
)
def __init__(self, *args, **kwargs):
"""Initialize form with year choices derived from existing benefit and package years."""
super().__init__(*args, **kwargs)
benefits_years = list(SponsorshipBenefit.objects.values_list("year", flat=True).distinct())
packages_years = list(SponsorshipPackage.objects.values_list("year", flat=True).distinct())
choices = [(y, y) for y in sorted(set(benefits_years + packages_years), reverse=True) if y]
self.fields["from_year"].choices = choices
@property
def configured_years(self):
"""Return the list of years that have existing configurations."""
return [c[0] for c in self.fields["from_year"].choices]
MAX_TARGET_YEAR = 2050
def clean_target_year(self):
"""Validate that the target year does not exceed the maximum allowed year."""
data = self.cleaned_data["target_year"]
if data > self.MAX_TARGET_YEAR:
msg = f"The target year can't be bigger than {self.MAX_TARGET_YEAR}."
raise forms.ValidationError(msg)
return data
def clean_from_year(self):
"""Convert the from_year field value to an integer."""
return int(self.cleaned_data["from_year"])
def clean(self):
"""Validate that the target year is greater than the source and has no existing config."""
from_year = self.cleaned_data.get("from_year")
target_year = self.cleaned_data.get("target_year")
if from_year and target_year:
if target_year < from_year:
msg = "The target year must be greater the one used as source."
raise forms.ValidationError(msg)
if target_year in self.configured_years:
msg = f"The year {target_year} already have a valid confguration."
raise forms.ValidationError(msg)
return self.cleaned_data