-
Notifications
You must be signed in to change notification settings - Fork 236
/
views.py
4598 lines (3933 loc) · 191 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
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
from betterforms.multiform import MultiModelForm
from datetime import datetime, timedelta, timezone
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.core import mail
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
from django.db import models
from django.forms import inlineformset_factory, ModelForm, modelform_factory, modelformset_factory, ValidationError
from django.forms import widgets
from django.forms.models import BaseInlineFormSet, BaseModelFormSet
from django.http import JsonResponse, HttpResponse, Http404
from django.shortcuts import get_list_or_404
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.http import urlencode
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.views.decorators.http import require_POST
from django.views.generic import FormView, View, DetailView, ListView, TemplateView
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.views.generic.detail import SingleObjectMixin
from formtools.wizard.views import SessionWizardView
from itertools import chain, groupby
import json
from markdownx.utils import markdownify
from django_registration.forms import RegistrationForm
from django_registration.backends.activation import views as activation_views
import reversion
from . import email
from .dashboard import get_dashboard_sections
from .forms import InviteForm
from .forms import CommunityNameForm
from .forms import RenameProjectSkillsForm
from .forms import RadioBooleanField
from .mixins import ApprovalStatusAction
from .mixins import ComradeRequiredMixin
from .mixins import EligibleApplicantRequiredMixin
from .mixins import Preview
from .models import AlumInfo
from .models import ApplicantApproval
from .models import ApplicantGenderIdentity
from .models import ApplicantRaceEthnicityInformation
from .models import ApplicationReviewer
from .models import ApprovalStatus
from .models import BarriersToParticipation
from .models import CohortPage
from .models import CommunicationChannel
from .models import Community
from .models import Comrade
from .models import ContractorInformation
from .models import Contribution
from .models import CoordinatorApproval
from .models import EmploymentTimeCommitment
from .models import FinalApplication
from .models import get_deadline_date_for
from .models import InformalChatContact
from .models import InternSelection
from .models import InitialApplicationReview
from .models import Feedback1FromMentor
from .models import Feedback1FromIntern
from .models import Feedback2FromMentor
from .models import Feedback2FromIntern
from .models import Feedback3FromMentor
from .models import Feedback3FromIntern
from .models import Feedback4FromMentor
from .models import Feedback4FromIntern
from .models import FinalMentorFeedback
from .models import FinalInternFeedback
from .models import MentorApproval
from .models import MentorRelationship
from .models import NewCommunity
from .models import NonCollegeSchoolTimeCommitment
from .models import Notification
from .models import OrganizerNotes
from .models import Participation
from .models import PaymentEligibility
from .models import PriorFOSSExperience
from .models import Project
from .models import ProjectSkill
from .models import PromotionTracking
from .models import Role
from .models import RoundPage
from .models import skill_is_valid
from .models import SchoolInformation
from .models import SchoolTimeCommitment
from .models import TimeCommitmentSummary
from .models import SignedContract
from .models import Sponsorship
from .models import VolunteerTimeCommitment
from .models import WorkEligibility
from os import path
class RegisterUserForm(RegistrationForm):
def clean(self):
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exists():
self.add_error('email', mark_safe('This email address is already associated with an account. If you have forgotten your password, you can <a href="{}">reset it</a>.'.format(reverse('password_reset'))))
super(RegisterUserForm, self).clean()
class RegisterUser(activation_views.RegistrationView):
form_class = RegisterUserForm
# The RegistrationView that django-registration provides
# doesn't respect the next query parameter, so we have to
# add it to the context of the template.
def get_context_data(self, **kwargs):
context = super(RegisterUser, self).get_context_data(**kwargs)
context['next'] = self.request.GET.get('next', '/')
return context
def get_activation_key(self, user):
# The superclass implementation of get_activation_key will
# serialize arbitrary data in JSON format, so we can save more
# data than just the username, which is good! Unfortunately it
# expects to get that data by calling a get_username method,
# which only works for actual Django user models. So first we
# construct a fake user model for it to take apart, containing
# only the data we want.
self.activation_data = {'u': user.username}
# Now, if we have someplace the user is supposed to go after
# registering, then we save that as well.
next_url = self.request.POST.get('next')
if next_url:
self.activation_data['n'] = next_url
return super(RegisterUser, self).get_activation_key(self)
def get_username(self):
return self.activation_data
def get_email_field_name(self):
return "email"
def get_email_context(self, activation_key):
return {
'activation_key': activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'request': self.request,
}
class PendingRegisterUser(TemplateView):
template_name = 'django_registration/registration_complete.html'
class ActivationView(activation_views.ActivationView):
def get_user(self, data):
# In the above RegistrationView, we dumped extra data into the
# activation key, but the superclass implementation of get_user
# expects the key to contain only a username string. So we save
# our extra data and then pass the superclass the part it
# expected.
self.next_url = data.get('n')
return super(ActivationView, self).get_user(data['u'])
def get_success_url(self, user):
# Ugh, we need to chain together TWO next-page URLs so we can
# confirm that the person who posesses this activation token
# also knows the corresponding password, then make a stop at the
# ComradeUpdate form, before finally going where the user
# actually wanted to go. Sorry folks.
if self.next_url:
query = '?' + urlencode({'next': self.next_url})
else:
query = ''
query = '?' + urlencode({'next': reverse('account') + query})
return reverse('django_registration_activation_complete') + query
class ActivationCompleteView(TemplateView):
template_name = 'django_registration/activation_complete.html'
class OrganizerNotesUpdate(LoginRequiredMixin, ComradeRequiredMixin, UpdateView):
model = OrganizerNotes
fields = ['status', 'notes',]
def get_object(self):
if not self.request.user.is_staff:
raise PermissionDenied("Only Outreachy organizers can edit notes.")
# If the comrade already has associated notes, fetch the notes object.
# Otherwise create a new OrganizerNotes object.
comrade = get_object_or_404(Comrade, pk=self.kwargs['comrade_pk'])
if not comrade.organizer_notes:
return OrganizerNotes(comrade=comrade)
return comrade.organizer_notes
def get_success_url(self):
comrade = get_object_or_404(Comrade, pk=self.kwargs['comrade_pk'])
comrade.organizer_notes = self.object
comrade.save()
return self.request.GET.get('next', reverse('dashboard'))
# FIXME - we need a way for comrades to update and re-verify their email address.
class ComradeUpdate(LoginRequiredMixin, reversion.views.RevisionMixin, UpdateView):
fields = [
'public_name',
'legal_name',
'pronouns',
'pronouns_to_participants',
'pronouns_public',
'photo',
'timezone',
'location',
'github_url',
'gitlab_url',
'nick',
'blog_url',
'blog_rss_url',
'twitter_url',
'mastodon_url',
'agreed_to_code_of_conduct',
]
def get_object(self):
# Either grab the current comrade to update, or make a new one
try:
return self.request.user.comrade
except Comrade.DoesNotExist:
return Comrade(account=self.request.user)
def get_context_data(self, **kwargs):
context = super(ComradeUpdate, self).get_context_data(**kwargs)
context['next'] = self.request.GET.get('next', '/')
with open(path.join(settings.BASE_DIR, 'CODE-OF-CONDUCT.md')) as coc_file:
context['codeofconduct'] = markdownify(coc_file.read())
return context
# FIXME - not sure where we should redirect people back to?
# Take them back to the home page right now.
def get_success_url(self):
return self.request.POST.get('next', '/')
class EmptyModelFormSet(BaseModelFormSet):
def get_queryset(self):
return self.model._default_manager.none()
class SchoolTimeCommitmentModelFormSet(EmptyModelFormSet):
def clean(self):
super(SchoolTimeCommitmentModelFormSet, self).clean()
if any(self.errors):
# Don't validate if the individual term fields already have errors
return
end = None
last_term = None
number_filled_terms = 0
for index, form in enumerate(self.forms):
# This checks if one of the forms was left blank
if index >= self.initial_form_count() and not form.has_changed():
continue
number_filled_terms += 1
# Ensure that only one term has last_term set
end_term = form.cleaned_data['last_term']
if end_term:
if last_term:
raise ValidationError("You cannot have more than one term be the last term in your degree.")
else:
last_term = form
# Ensure terms are in consecutive order
start_date = form.cleaned_data['start_date']
if end and end > start_date:
raise ValidationError("Terms must be in chronological order.")
end = form.cleaned_data['end_date']
# Ensure that all three terms are filled out, unless one term has the last_term set
if not last_term and number_filled_terms < 3:
raise ValidationError("Please provide information for your next three terms of classes.")
# We can't confirm there are no terms after the term where last_term is set
# because someone might be ending their bachelor's degree and starting a master's.
def work_eligibility_is_approved(wizard):
cleaned_data = wizard.get_cleaned_data_for_step('Work Eligibility')
if not cleaned_data:
return True
if not cleaned_data['over_18']:
return False
# If they have student visa restrictions, we don't follow up
# until they're actually selected as an intern, at which point we
# need to send them a CPT letter and have them get it approved.
if not cleaned_data['eligible_to_work']:
return False
if cleaned_data['under_export_control']:
return False
# If they're in a us_sanctioned_country, go ahead and collect the
# rest of the information on the forms, but we'll mark them as
# PENDING later.
return True
def prior_foss_experience_is_approved(wizard):
if not work_eligibility_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Prior FOSS Experience')
if not cleaned_data:
return True
if cleaned_data['gsoc_or_outreachy_internship']:
return False
return True
def show_us_demographics(wizard):
if not prior_foss_experience_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Payment Eligibility') or {}
if not cleaned_data:
return True
us_resident = cleaned_data.get('us_national_or_permanent_resident', True)
return us_resident
def show_noncollege_school_info(wizard):
if not prior_foss_experience_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Time Commitments') or {}
return cleaned_data.get('enrolled_as_noncollege_student', True)
def show_school_info(wizard):
if not prior_foss_experience_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Time Commitments') or {}
return cleaned_data.get('enrolled_as_student', True)
def show_contractor_info(wizard):
if not prior_foss_experience_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Time Commitments') or {}
if cleaned_data == None:
return False
return cleaned_data.get('contractor', True)
def show_employment_info(wizard):
if not prior_foss_experience_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Time Commitments') or {}
if cleaned_data.get('employed', True):
return True
if cleaned_data.get('contractor', True):
cleaned_data = wizard.get_cleaned_data_for_step('Contractor Info')
if cleaned_data and cleaned_data[0].get('continuing_contract_work', True):
return True
return False
def show_time_commitment_info(wizard):
if not prior_foss_experience_is_approved(wizard):
return False
cleaned_data = wizard.get_cleaned_data_for_step('Time Commitments') or {}
return cleaned_data.get('volunteer_time_commitments', True)
def determine_eligibility(wizard, applicant):
if not (work_eligibility_is_approved(wizard)):
return (ApprovalStatus.REJECTED, 'GENERAL')
if not (prior_foss_experience_is_approved(wizard)):
return (ApprovalStatus.REJECTED, 'GENERAL')
days_free = applicant.get_time_commitments()["longest_period_free"]
if days_free is None or days_free < applicant.required_days_free():
return (ApprovalStatus.REJECTED, 'TIME')
general_data = wizard.get_cleaned_data_for_step('Work Eligibility')
if general_data['us_sanctioned_country']:
return (ApprovalStatus.PENDING, 'SANCTIONED')
return (ApprovalStatus.PENDING, 'ESSAY')
def get_current_round_for_initial_application():
"""
People can only submit new initial applications or edit initial
applications when the application period is open.
"""
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
try:
current_round = RoundPage.objects.get(
initial_applications_open__lte=today,
initial_applications_close__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
raise PermissionDenied('The Outreachy application period is closed. If you are an applicant who has submitted an application for an internship project and your time commitments have increased, please contact the Outreachy organizers (see contact link above). Eligibility checking will become available when the next application period opens. Please sign up for the announcements mailing list for an email when the next application period opens: https://lists.outreachy.org/cgi-bin/mailman/listinfo/announce')
return current_round
def get_current_round_for_initial_application_review():
"""
Application reviewers need to have finished their work before the
contribution period begins.
"""
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
try:
current_round = RoundPage.objects.get(
initial_applications_open__lte=today,
internstarts__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
raise PermissionDenied('It is too late to review applications.')
return current_round
def get_current_round_for_sponsors():
"""
We want to engage sponsors until the interns are announced.
Otherwise we'll show the generic round schedule.
"""
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
try:
current_round = RoundPage.objects.get(
internannounce__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
return None
return current_round
def get_current_round_for_community_signup():
"""
Find the current round with an open call for communities.
"""
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
try:
current_round = RoundPage.objects.get(
contributions_open__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
return None
return current_round
class EligibilityUpdateView(LoginRequiredMixin, ComradeRequiredMixin, SessionWizardView):
template_name = 'home/wizard_form.html'
condition_dict = {
'Payment Eligibility': work_eligibility_is_approved,
'Prior FOSS Experience': work_eligibility_is_approved,
'USA demographics': show_us_demographics,
'Gender Identity': prior_foss_experience_is_approved,
'Time Commitments': prior_foss_experience_is_approved,
'School Info': show_school_info,
'School Term Info': show_school_info,
'Coding School or Online Courses Time Commitment Info': show_noncollege_school_info,
'Contractor Info': show_contractor_info,
'Employment Info': show_employment_info,
'Volunteer Time Commitment Info': show_time_commitment_info,
}
form_list = [
('Work Eligibility', modelform_factory(WorkEligibility,
fields=(
'over_18',
'student_visa_restrictions',
'eligible_to_work',
'under_export_control',
'us_sanctioned_country',
),
field_classes={
'over_18': RadioBooleanField,
'student_visa_restrictions': RadioBooleanField,
'eligible_to_work': RadioBooleanField,
'under_export_control': RadioBooleanField,
'us_sanctioned_country': RadioBooleanField,
},
)),
('Payment Eligibility', modelform_factory(PaymentEligibility,
fields=(
'us_national_or_permanent_resident',
'living_in_us',
),
field_classes={
'us_national_or_permanent_resident': RadioBooleanField,
'living_in_us': RadioBooleanField,
},
)),
('Prior FOSS Experience', modelform_factory(PriorFOSSExperience,
fields=(
'gsoc_or_outreachy_internship',
'prior_contributor',
'prior_paid_contributor',
),
field_classes={
'gsoc_or_outreachy_internship': RadioBooleanField,
'prior_contributor': RadioBooleanField,
'prior_paid_contributor': RadioBooleanField,
},
)),
('USA demographics', modelform_factory(ApplicantRaceEthnicityInformation,
fields=(
'us_resident_demographics',
),
field_classes={
'us_resident_demographics': RadioBooleanField,
},
)),
('Gender Identity', modelform_factory(ApplicantGenderIdentity, fields=(
'transgender',
'genderqueer',
'man',
'woman',
'demi_boy',
'demi_girl',
'trans_masculine',
'trans_feminine',
'non_binary',
'demi_non_binary',
'genderqueer',
'genderflux',
'genderfluid',
'demi_genderfluid',
'demi_gender',
'bi_gender',
'tri_gender',
'multigender',
'pangender',
'maxigender',
'aporagender',
'intergender',
'mavrique',
'gender_confusion',
'gender_indifferent',
'graygender',
'agender',
'genderless',
'gender_neutral',
'neutrois',
'androgynous',
'androgyne',
'prefer_not_to_say',
'self_identify',
),
field_classes={
'transgender': RadioBooleanField,
'genderqueer': RadioBooleanField,
},
)),
('Barriers-to-Participation', modelform_factory(BarriersToParticipation,
fields=(
'country_living_in_during_internship',
'country_living_in_during_internship_code',
'underrepresentation',
'employment_bias',
'lacking_representation',
'systemic_bias',
'content_warnings',
),
widgets={
'country_living_in_during_internship_code': widgets.HiddenInput,
},
)),
('Time Commitments', modelform_factory(TimeCommitmentSummary,
fields=(
'enrolled_as_student',
'enrolled_as_noncollege_student',
'employed',
'contractor',
'volunteer_time_commitments',
),
field_classes={
'enrolled_as_student': RadioBooleanField,
'enrolled_as_noncollege_student': RadioBooleanField,
'employed': RadioBooleanField,
'contractor': RadioBooleanField,
'volunteer_time_commitments': RadioBooleanField,
},
)),
('School Info', modelform_factory(SchoolInformation,
fields=(
'university_name',
'university_website',
'current_academic_calendar',
'next_academic_calendar',
'degree_name',
),
)),
('School Term Info', modelformset_factory(SchoolTimeCommitment,
formset=SchoolTimeCommitmentModelFormSet,
min_num=1,
validate_min=True,
extra=2,
can_delete=False,
fields=(
'term_name',
'start_date',
'end_date',
'last_term',
),
)),
('Coding School or Online Courses Time Commitment Info', modelformset_factory(NonCollegeSchoolTimeCommitment,
formset=EmptyModelFormSet,
min_num=1,
validate_min=True,
extra=4,
can_delete=False,
fields=(
'start_date',
'end_date',
'hours_per_week',
'description',
'quit_on_acceptance',
),
)),
('Contractor Info', modelformset_factory(ContractorInformation,
formset=EmptyModelFormSet,
min_num=1,
max_num=1,
validate_min=True,
validate_max=True,
can_delete=False,
fields=(
'typical_hours',
'continuing_contract_work',
),
field_classes={
'continuing_contract_work': RadioBooleanField,
},
)),
('Employment Info', modelformset_factory(EmploymentTimeCommitment,
formset=EmptyModelFormSet,
min_num=1,
validate_min=True,
extra=2,
can_delete=False,
fields=(
'start_date',
'end_date',
'hours_per_week',
'job_title',
'job_description',
'quit_on_acceptance',
),
)),
('Volunteer Time Commitment Info', modelformset_factory(VolunteerTimeCommitment,
formset=EmptyModelFormSet,
min_num=1,
validate_min=True,
extra=2,
can_delete=False,
fields=(
'start_date',
'end_date',
'hours_per_week',
'description',
),
)),
('Outreachy Promotional Information', modelform_factory(PromotionTracking,
fields=(
'spread_the_word',
),
)),
]
TEMPLATES = {
'Work Eligibility': 'home/eligibility_wizard_general.html',
'Payment Eligibility': 'home/eligibility_wizard_tax_forms.html',
'Prior FOSS Experience': 'home/eligibility_wizard_foss_experience.html',
'USA demographics': 'home/eligibility_wizard_us_demographics.html',
'Gender Identity': 'home/eligibility_wizard_gender.html',
'Barriers-to-Participation': 'home/eligibility_wizard_essay_questions.html',
'Time Commitments': 'home/eligibility_wizard_time_commitments.html',
'School Info': 'home/eligibility_wizard_school_info.html',
'School Term Info': 'home/eligibility_wizard_school_terms.html',
'Coding School or Online Courses Time Commitment Info': 'home/eligibility_wizard_noncollege_school_info.html',
'Contractor Info': 'home/eligibility_wizard_contractor_info.html',
'Employment Info': 'home/eligibility_wizard_employment_info.html',
'Volunteer Time Commitment Info': 'home/eligibility_wizard_time_commitment_info.html',
'Outreachy Promotional Information': 'home/eligibility_wizard_promotional.html',
}
def get_template_names(self):
return [self.TEMPLATES[self.steps.current]]
def show_results_if_any(self):
# get_context_data() and done() both need a round; save it for them.
self.current_round = get_current_round_for_initial_application()
already_submitted = ApplicantApproval.objects.filter(
applicant=self.request.user.comrade,
application_round=self.current_round,
).exists()
if not already_submitted:
# Continue with the default get or post behavior.
return None
return redirect(self.request.GET.get('next', reverse('eligibility-results')))
def get(self, *args, **kwargs):
# Using `or` this way returns the redirect from show_results_if_any,
# unless that function returns None. Only in that case does it call the
# superclass implementation of this method and return _that_.
return self.show_results_if_any() or super(EligibilityUpdateView, self).get(*args, **kwargs)
def post(self, *args, **kwargs):
# See self.get(), above.
return self.show_results_if_any() or super(EligibilityUpdateView, self).post(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(EligibilityUpdateView, self).get_context_data(**kwargs)
context['current_round'] = self.current_round
return context
def done(self, form_list, **kwargs):
# Make sure to commit the object to the database before saving
# any of the related objects, so they can set their foreign keys
# to point to this ApplicantApproval object.
self.object = ApplicantApproval.objects.create(
applicant=self.request.user.comrade,
application_round=self.current_round,
ip_address=self.request.META.get('REMOTE_ADDR'),
)
for form in form_list:
results = form.save(commit=False)
# result might be a single value because it's a modelform
# (WorkEligibility and TimeCommitmentSummary)
# or a list because it's a modelformsets
# (VolunteerTimeCommitment, EmploymentTimeCommitment, etc)
# Make it into a list if it isn't one already.
if not isinstance(results, list):
results = [ results ]
# For each object which contains data from the modelform
# or modelformsets, we save that database object,
# after setting the parent pointer.
for r in results:
r.applicant = self.object
r.save()
# Now that all the related objects are saved, we can determine
# elegibility from them, which avoids duplicating some code that's
# already on the models. The cost is reading back some of the objects
# we just wrote and then re-saving an object, but that isn't a big hit.
self.object.approval_status, self.object.reason_denied = determine_eligibility(self, self.object)
# Save the country and country code
# in a field for Software Freedom Conservancy accounting
cleaned_data = self.get_cleaned_data_for_step('Barriers-to-Participation')
if cleaned_data:
self.object.initial_application_country_living_in_during_internship = cleaned_data['country_living_in_during_internship']
self.object.initial_application_country_living_in_during_internship_code = cleaned_data['country_living_in_during_internship_code']
self.object.save()
return redirect(self.request.GET.get('next', reverse('eligibility-results')))
class EligibilityResults(LoginRequiredMixin, ComradeRequiredMixin, DetailView):
template_name = 'home/eligibility_results.html'
context_object_name = 'role'
def get_object(self):
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
# We want to let people know why they can't make contributions, right
# up until all contributions are closed; but we don't want to confuse
# people who come back in a future round by showing them old results.
try:
current_round = RoundPage.objects.get(
initial_applications_open__lte=today,
contributions_close__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
raise PermissionDenied('The Outreachy application period is closed. Eligibility checking will become available when the next application period opens. Please sign up for the announcements mailing list for an email when the next application period opens: https://lists.outreachy.org/cgi-bin/mailman/listinfo/announce')
role = Role(self.request.user, current_round)
if not role.is_applicant:
raise Http404("No initial application in this round.")
return role
class ViewInitialApplication(LoginRequiredMixin, ComradeRequiredMixin, DetailView):
template_name = 'home/applicant_review_detail.html'
context_object_name = 'application'
def get_context_data(self, **kwargs):
context = super(ViewInitialApplication, self).get_context_data(**kwargs)
context['current_round'] = self.object.application_round
context['role'] = self.role
return context
def get_object(self):
current_round = get_current_round_for_initial_application_review()
self.role = Role(self.request.user, current_round)
if not self.role.is_organizer and not self.role.is_reviewer:
raise PermissionDenied("You are not authorized to review applications.")
return get_object_or_404(ApplicantApproval,
applicant__account__username=self.kwargs['applicant_username'],
application_round=current_round)
class ProcessInitialApplication(LoginRequiredMixin, ComradeRequiredMixin, DetailView):
template_name = 'home/process_initial_application.html'
context_object_name = 'application'
def get_context_data(self, **kwargs):
context = super(ProcessInitialApplication, self).get_context_data(**kwargs)
context['current_round'] = self.object.application_round
context['role'] = self.role
return context
def get_object(self):
current_round = get_current_round_for_initial_application_review()
self.role = Role(self.request.user, current_round)
if not self.role.is_organizer and not self.role.is_reviewer:
raise PermissionDenied("You are not authorized to review applications.")
return get_object_or_404(ApplicantApproval,
applicant__account__username=self.kwargs['applicant_username'],
application_round=current_round)
def promote_page(request):
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
# For the purposes of this view, a round is current until
# initial application period ends. After that, there's
# no point in getting people to apply to that round.
try:
current_round = RoundPage.objects.get(
pingnew__lte=today,
initial_applications_close__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
current_round = None
return render(request, 'home/promote.html',
{
'current_round' : current_round,
},
)
def past_rounds_page(request):
return render(request, 'home/past_rounds.html',
{
'rounds' : RoundPage.objects.all().order_by('internstarts'),
},
)
def current_round_page(request):
closed_approved_projects = []
ontime_approved_projects = []
example_skill = ProjectSkill
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
# For the purposes of this view, a round is current until its
# intern selections are announced, and then it becomes one of
# the "previous" rounds.
try:
previous_round = RoundPage.objects.filter(
internannounce__lte=today,
).latest('internstarts')
previous_round.today = today
except RoundPage.DoesNotExist:
previous_round = None
try:
# Keep RoundPage.serve() in sync with this.
current_round = RoundPage.objects.get(
pingnew__lte=today,
internannounce__gt=today,
)
current_round.today = today
except RoundPage.DoesNotExist:
current_round = None
role = Role(request.user, current_round)
if current_round is not None:
all_participations = current_round.participation_set.approved().order_by('community__name')
apps_open = current_round.initial_applications_open.has_passed()
if apps_open or role.is_volunteer:
# Anyone should be able to see all projects if the initial
# application period is open. This builds up excitement in
# applicants and gets them to complete an initial application. Note
# in the template, links are still hidden if the initial
# application is pending or rejected.
approved_participations = all_participations
elif request.user.is_authenticated:
# Approved coordinators should be able to see their communities
# even if the community isn't approved yet.
approved_participations = all_participations.filter(
community__coordinatorapproval__approval_status=ApprovalStatus.APPROVED,
community__coordinatorapproval__coordinator__account=request.user,
)
else:
# Otherwise, no communities should be visible.
approved_participations = all_participations.none()
for p in approved_participations:
projects = p.project_set.approved().filter(new_contributors_welcome=False)
if projects:
closed_approved_projects.append((p, projects))
projects = p.project_set.approved().filter(new_contributors_welcome=True)
if projects:
ontime_approved_projects.append((p, projects))
# List communities that are approved but don't have any projects yet
if not p.project_set.approved():
ontime_approved_projects.append((p, None))
return render(request, 'home/round_page_with_communities.html',
{
'current_round' : current_round,
'previous_round' : previous_round,
'closed_projects': closed_approved_projects,
'ontime_projects': ontime_approved_projects,
'example_skill': example_skill,
'role': role,
},
)
# Call for communities, mentors, and volunteers page
#
# This is complex, so class-based views don't help us here.
#
# We want to display four sections:
# * Blurb about what Outreachy is
# * Timeline for the round
# * Communities that are participating and are open to mentors and volunteers
# * Communities that have participated and need to be claimed by coordinators
#
# We need to end up with:
# * The most current round (by round number)
# * The communities participating in the current round (which have their CFP open)
# * The communities which aren't participating in the current round
#
# We need to do some database calls in order to get this info:
# * Grab all the rounds, sort by round number (descending), hand us back one round
# * For the current round, grab all Participations (communities participating)
# * Grab all the communities
#
# To get the communities which aren't participating:
# * Make a set of the community IDs from the communities
# participating in the current round (participating IDs)
# * Walk through all communities, seeing if the community ID is
# in participating IDs.
# * If so, put it in a participating communities set
# * If not, put it in a not participating communities set
def community_cfp_view(request):
# Cheap trick for case-insensitive sorting: the slug is always lower-cased.
all_communities = Community.objects.all().order_by('slug')
approved_communities = []
pending_communities = []
rejected_communities = []
not_participating_communities = []
# The problem here is the CFP page serves four (or more) purposes:
# - to provide mentors a way to submit new projects
# - to provide coordinators a way to submit new communities
# - to allow mentors to sign up to co-mentor a project
# - to allow mentors a way to edit their projects
#
# So, we close down the page after the interns are announced,
# when (hopefully) all mentors have signed up to co-mentor.
# Mentors can still be sent a manual link to sign up to co-mentor after that date,
# but their community page just won't show their project.
now = datetime.now(timezone.utc)
today = get_deadline_date_for(now)
try:
previous_round = RoundPage.objects.filter(
internstarts__lte=today,
).latest('internstarts')