def assign_repeat_achievements(instance, repeat_positions): twice_same_position = get_object_or_none(Achievement, short_name='twice_same_position') thrice_same_position = get_object_or_none( Achievement, short_name='thrice_same_position') two_repeated_positions = get_object_or_none( Achievement, short_name='two_repeated_positions') twice_held_positions = set() num_unique_twice_held_positions = 0 for sequence in repeat_positions: if len(sequence['positions']) >= 2: if twice_same_position: twice_same_position.assign(instance.user, term=sequence['terms'][1]) if sequence['positions'][0] not in twice_held_positions: twice_held_positions.add(sequence['positions'][0]) num_unique_twice_held_positions += 1 if num_unique_twice_held_positions == 2: if two_repeated_positions: two_repeated_positions.assign(instance.user, term=sequence['terms'][1]) if len(sequence['positions']) >= 3: if thrice_same_position: thrice_same_position.assign(instance.user, term=sequence['terms'][2])
def test_candidate_post_save(self): student_org_profile = get_object_or_none( StudentOrgUserProfile, user=self.user) # Candidate has already been saved for this user created above, so # StudentOrgUserProfile should exist: self.assertIsNotNone(student_org_profile) # Candidate has not been marked as initiated, so initiation_term should # be None in their profile, and the candidate should be in the Current # Candidate group and not in the Member group: self.assertIsNone(student_org_profile.initiation_term) candidate_groups = self.candidate.user.groups.all() self.assertIn(self.candidate_group, candidate_groups) self.assertNotIn(self.member_group, candidate_groups) # Mark candidate as initiated, so profile and groups should update to # match: self.candidate.initiated = True self.candidate.save() student_org_profile = get_object_or_none( StudentOrgUserProfile, user=self.user) self.assertEqual(student_org_profile.initiation_term, self.term) candidate_groups = self.candidate.user.groups.all() self.assertNotIn(self.candidate_group, candidate_groups) self.assertIn(self.member_group, candidate_groups)
def test_autocreate_project_report(self): """ Ensures that when an EventForm is saved, a project report corresponding to that event is created, depending on the needs_pr field. """ # Create the fields for an Event, based on the event created in setUp, # simply with a different event name event_name_no_pr = 'My Event Without a PR' event_name_pr = 'My Event With a PR' fields = { 'name': event_name_no_pr, 'event_type': self.event.event_type.pk, 'term': self.event.term.pk, 'contact': self.user.pk, 'committee': self.event.committee.pk, 'restriction': Event.OFFICER, 'location': self.event.location, 'requirements_credit': self.event.requirements_credit, 'max_guests_per_person': self.event.max_guests_per_person, 'signup_limit': self.event.signup_limit, 'start_datetime_0': self.start_date, 'start_datetime_1': self.start_time, 'end_datetime_0': self.end_date, 'end_datetime_1': self.end_time, 'needs_pr': False } # Ensure that saving the EventForm creates the event and that no # project report is created: EventForm(fields).save() event = get_object_or_none(Event, name=event_name_no_pr) self.assertIsNotNone(event) self.assertIsNone(event.project_report) self.assertFalse(ProjectReport.objects.all().exists()) # Create event with form, requiring project report, and ensure PR # is created: fields.update({'name': event_name_pr, 'needs_pr': True}) EventForm(fields).save() event = get_object_or_none(Event, name=event_name_pr) self.assertIsNotNone(event) self.assertTrue(ProjectReport.objects.all().exists()) project_report = ProjectReport.objects.all()[0] # Check the properties of both the event and project report to ensure # that they were saved and match our form self.assertEqual(event.name, event_name_pr) self.assertEqual(project_report.title, event_name_pr) self.assertEqual(event.start_datetime.date(), self.event.start_datetime.date()) self.assertEqual(project_report.date, self.event.start_datetime.date()) self.assertEqual(event.contact, self.user) self.assertEqual(project_report.author, self.user) self.assertEqual(event.term, self.event.term) self.assertEqual(project_report.term, self.event.term) self.assertEqual(project_report, event.project_report)
def assign_repeat_achievements(instance, repeat_positions): twice_same_position = get_object_or_none( Achievement, short_name='twice_same_position') thrice_same_position = get_object_or_none( Achievement, short_name='thrice_same_position') two_repeated_positions = get_object_or_none( Achievement, short_name='two_repeated_positions') twice_held_positions = set() num_unique_twice_held_positions = 0 for sequence in repeat_positions: if len(sequence['positions']) >= 2: if twice_same_position: twice_same_position.assign( instance.user, term=sequence['terms'][1]) if sequence['positions'][0] not in twice_held_positions: twice_held_positions.add(sequence['positions'][0]) num_unique_twice_held_positions += 1 if num_unique_twice_held_positions == 2: if two_repeated_positions: two_repeated_positions.assign( instance.user, term=sequence['terms'][1]) if len(sequence['positions']) >= 3: if thrice_same_position: thrice_same_position.assign( instance.user, term=sequence['terms'][2])
def assign_specific_event_achievements(instance): d15_regex = re.compile(r'.*D(istrict)?[\s]?15.*') if d15_regex.match(instance.event.name): d15_achievement = get_object_or_none(Achievement, short_name='attend_d15') if d15_achievement: d15_achievement.assign(instance.user, term=instance.event.term) if 'National Convention' in instance.event.name: natl_achievement = get_object_or_none(Achievement, short_name='attend_convention') if natl_achievement: natl_achievement.assign(instance.user, term=instance.event.term) if 'Envelope Stuffing' in instance.event.name: envelope_achievement = get_object_or_none( Achievement, short_name='attend_envelope_stuffing') if envelope_achievement: envelope_achievement.assign(instance.user, term=instance.event.term) if instance.event.name == 'Candidate Meeting' and ( instance.event.term == Term(term=Term.FALL, year=2013)): cm2013_achievement = get_object_or_none( Achievement, short_name='berkeley_explosion') if cm2013_achievement: cm2013_achievement.assign(instance.user, term=instance.event.term)
def assign_chair_achievements(instance, chair_terms): num_committees_chaired = len(chair_terms) chair1achievement = get_object_or_none( Achievement, short_name='chair1committee') chair2achievement = get_object_or_none( Achievement, short_name='chair2committees') if num_committees_chaired >= 1: # terms is a list of lists terms = chair_terms.values() if chair1achievement: # for the first committee that was chaired, find the first term # that they were chair chair1_terms = terms[0] chair1achievement.assign( instance.user, term=chair1_terms[0]) if chair2achievement: if num_committees_chaired >= 2: # for the second committee that was chaired, find the first # term that they were chair chair2_terms = terms[1] chair2achievement.assign( instance.user, term=chair2_terms[0]) else: chair2achievement.assign( instance.user, acquired=False, progress=1)
def test_autocreate_project_report(self): """ Ensures that when an EventForm is saved, a project report corresponding to that event is created, depending on the needs_pr field. """ # Create the fields for an Event, based on the event created in setUp, # simply with a different event name event_name_no_pr = 'My Event Without a PR' event_name_pr = 'My Event With a PR' fields = {'name': event_name_no_pr, 'event_type': self.event.event_type.pk, 'term': self.event.term.pk, 'contact': self.user.pk, 'committee': self.event.committee.pk, 'restriction': Event.OFFICER, 'location': self.event.location, 'requirements_credit': self.event.requirements_credit, 'max_guests_per_person': self.event.max_guests_per_person, 'signup_limit': self.event.signup_limit, 'start_datetime_0': self.start_date, 'start_datetime_1': self.start_time, 'end_datetime_0': self.end_date, 'end_datetime_1': self.end_time, 'needs_pr': False} # Ensure that saving the EventForm creates the event and that no # project report is created: EventForm(fields).save() event = get_object_or_none(Event, name=event_name_no_pr) self.assertIsNotNone(event) self.assertIsNone(event.project_report) self.assertFalse(ProjectReport.objects.all().exists()) # Create event with form, requiring project report, and ensure PR # is created: fields.update({'name': event_name_pr, 'needs_pr': True}) EventForm(fields).save() event = get_object_or_none(Event, name=event_name_pr) self.assertIsNotNone(event) self.assertTrue(ProjectReport.objects.all().exists()) project_report = ProjectReport.objects.all()[0] # Check the properties of both the event and project report to ensure # that they were saved and match our form self.assertEqual(event.name, event_name_pr) self.assertEqual(project_report.title, event_name_pr) self.assertEqual(event.start_datetime.date(), self.event.start_datetime.date()) self.assertEqual(project_report.date, self.event.start_datetime.date()) self.assertEqual(event.contact, self.user) self.assertEqual(project_report.author, self.user) self.assertEqual(event.term, self.event.term) self.assertEqual(project_report.term, self.event.term) self.assertEqual(project_report, event.project_report)
def assign_chair_achievements(instance, chair_terms): num_committees_chaired = len(chair_terms) chair1achievement = get_object_or_none(Achievement, short_name='chair1committee') chair2achievement = get_object_or_none(Achievement, short_name='chair2committees') if num_committees_chaired >= 1: # terms is a list of lists terms = chair_terms.values() if chair1achievement: # for the first committee that was chaired, find the first term # that they were chair chair1_terms = terms[0] chair1achievement.assign(instance.user, term=chair1_terms[0]) if chair2achievement: if num_committees_chaired >= 2: # for the second committee that was chaired, find the first # term that they were chair chair2_terms = terms[1] chair2achievement.assign(instance.user, term=chair2_terms[0]) else: chair2achievement.assign(instance.user, acquired=False, progress=1)
def assign_specific_event_achievements(instance): d15_regex = re.compile(r'.*D(istrict)?[\s]?15.*') if d15_regex.match(instance.event.name): d15_achievement = get_object_or_none(Achievement, short_name='attend_d15') if d15_achievement: d15_achievement.assign(instance.user, term=instance.event.term) if 'National Convention' in instance.event.name: natl_achievement = get_object_or_none(Achievement, short_name='attend_convention') if natl_achievement: natl_achievement.assign(instance.user, term=instance.event.term) if 'Envelope Stuffing' in instance.event.name: envelope_achievement = get_object_or_none( Achievement, short_name='attend_envelope_stuffing') if envelope_achievement: envelope_achievement.assign(instance.user, term=instance.event.term) if instance.event.name == 'Candidate Meeting' and (instance.event.term == Term(term=Term.FALL, year=2013)): cm2013_achievement = get_object_or_none( Achievement, short_name='berkeley_explosion') if cm2013_achievement: cm2013_achievement.assign(instance.user, term=instance.event.term)
def dispatch(self, *args, **kwargs): self.current_term = Term.objects.get_current_term() self.event_types = EventType.objects.all() self.challenge_types = ChallengeType.objects.all() # Initialize req_lists to contain lists for every requirement type self.req_lists = {} for req in CandidateRequirement.REQUIREMENT_TYPE_CHOICES: self.req_lists[req[0]] = [] event_reqs = EventCandidateRequirement.objects.filter( term=self.current_term) # Create a list of requirements that at each index contains either a # requirement corresponding to an event type or None if there is no # requirement for the corresponding event type req_index = 0 for event_type in self.event_types: if req_index < event_reqs.count(): req = event_reqs[req_index] if req.event_type == event_type: self.req_lists[CandidateRequirement.EVENT].append(req) req_index += 1 continue self.req_lists[CandidateRequirement.EVENT].append(None) challenge_reqs = ChallengeCandidateRequirement.objects.filter( term=self.current_term) # Create a list of requirements that at each index contains either a # requirement corresponding to an challenge type or None if there is no # requirement for the corresponding challenge type req_index = 0 for challenge_type in self.challenge_types: if req_index < challenge_reqs.count(): req = challenge_reqs[req_index] if req.challenge_type == challenge_type: self.req_lists[CandidateRequirement.CHALLENGE].append(req) req_index += 1 continue self.req_lists[CandidateRequirement.CHALLENGE].append(None) exam_req = get_object_or_none(ExamFileCandidateRequirement, term=self.current_term) self.req_lists[CandidateRequirement.EXAM_FILE].append(exam_req) syllabus_req = get_object_or_none(SyllabusCandidateRequirement, term=self.current_term) self.req_lists[CandidateRequirement.SYLLABUS].append(syllabus_req) resume_req = get_object_or_none(ResumeCandidateRequirement, term=self.current_term) self.req_lists[CandidateRequirement.RESUME].append(resume_req) manual_reqs = ManualCandidateRequirement.objects.filter( term=self.current_term) for manual_req in manual_reqs: self.req_lists[CandidateRequirement.MANUAL].append(manual_req) return super(CandidateRequirementsEditView, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs): self.current_term = Term.objects.get_current_term() self.event_types = EventType.objects.all() self.challenge_types = ChallengeType.objects.all() # Initialize req_lists to contain lists for every requirement type self.req_lists = {} for req in CandidateRequirement.REQUIREMENT_TYPE_CHOICES: self.req_lists[req[0]] = [] event_reqs = EventCandidateRequirement.objects.filter( term=self.current_term) # Create a list of requirements that at each index contains either a # requirement corresponding to an event type or None if there is no # requirement for the corresponding event type req_index = 0 for event_type in self.event_types: if req_index < event_reqs.count(): req = event_reqs[req_index] if req.event_type == event_type: self.req_lists[CandidateRequirement.EVENT].append(req) req_index += 1 continue self.req_lists[CandidateRequirement.EVENT].append(None) challenge_reqs = ChallengeCandidateRequirement.objects.filter( term=self.current_term) # Create a list of requirements that at each index contains either a # requirement corresponding to an challenge type or None if there is no # requirement for the corresponding challenge type req_index = 0 for challenge_type in self.challenge_types: if req_index < challenge_reqs.count(): req = challenge_reqs[req_index] if req.challenge_type == challenge_type: self.req_lists[CandidateRequirement.CHALLENGE].append(req) req_index += 1 continue self.req_lists[CandidateRequirement.CHALLENGE].append(None) exam_req = get_object_or_none( ExamFileCandidateRequirement, term=self.current_term) self.req_lists[CandidateRequirement.EXAM_FILE].append(exam_req) resume_req = get_object_or_none( ResumeCandidateRequirement, term=self.current_term) self.req_lists[CandidateRequirement.RESUME].append(resume_req) manual_reqs = ManualCandidateRequirement.objects.filter( term=self.current_term) for manual_req in manual_reqs: self.req_lists[CandidateRequirement.MANUAL].append(manual_req) return super(CandidateRequirementsEditView, self).dispatch( *args, **kwargs)
def test_is_candidate(self): # No Candidate objects created yet: self.assertFalse(self.profile.is_candidate()) # Create Candidate for user in a past term: candidate = Candidate(user=self.user, term=self.term_old) candidate.save() # Should now be considered a candidate only if current=False: self.assertTrue(self.profile.is_candidate(current=False)) self.assertFalse(self.profile.is_candidate(current=True)) # Mark that candidate as initiated: candidate.initiated = True candidate.save() # Re-fetch profile since candidate save affects StudentOrgUserProfile # initiation_term field: self.profile = get_object_or_none(self.model, user=self.user) self.assertFalse(self.profile.is_candidate(current=False)) self.assertFalse(self.profile.is_candidate(current=True)) # Mark initiated as False, and create new Candidate for the current # Term, as is the case for a candidate who doesn't initiate one term # and returns as a candidate a later term: candidate.initiated = False candidate.save() candidate = Candidate(user=self.user, term=self.term) candidate.save() self.profile = get_object_or_none(self.model, user=self.user) # Should be now considered a candidate (initiated not True): self.assertTrue(self.profile.is_candidate(current=False)) self.assertTrue(self.profile.is_candidate(current=True)) # Mark that candidate as initiated: candidate.initiated = True candidate.save() self.profile = get_object_or_none(self.model, user=self.user) self.assertFalse(self.profile.is_candidate(current=False)) self.assertFalse(self.profile.is_candidate(current=True)) # Change the 'current' semester to an old semester: self.term_old.current = True self.term_old.save() # Now the candidate should be considered a candidate since they have # not _yet_ initiated based on what the current semester is, but # they are in the database as a candidate for the current semester: self.assertTrue(self.profile.is_candidate(current=False)) self.assertTrue(self.profile.is_candidate(current=True)) # Ensure that they are also marked as a candidate if initiated = False candidate.initiated = False candidate.save() self.profile = get_object_or_none(self.model, user=self.user) self.assertTrue(self.profile.is_candidate(current=False)) self.assertTrue(self.profile.is_candidate(current=True))
def set_course_instance(self, cleaned_data): """Check if a course is valid and whether a course instance exists with the exact instructors given, and create a course instance if one doesn't exist. """ department = self.cleaned_data.get('department') course_number = self.cleaned_data.get('course_number') term = self.cleaned_data.get('term') course = get_object_or_none(Course, department=department, number=course_number) if not course: error_msg = '{department} {number} does not exist.'.format( department=department, number=course_number) self._errors['department'] = self.error_class([error_msg]) self._errors['course_number'] = self.error_class([error_msg]) raise forms.ValidationError('Invalid course') # check instructors to prevent trying to iterate over nothing self.exam_instructors = self.cleaned_data.get('instructors') if not self.exam_instructors: raise forms.ValidationError('Please fill out all fields.') # check whether each instructor has given permission for their exams for instructor in self.exam_instructors: instructor_permission = get_object_or_none(InstructorPermission, instructor=instructor) if instructor_permission and \ not instructor_permission.permission_allowed: error_msg = 'Instructor {name} has requested that their' \ 'exams not be uploaded to our exam files' \ 'database.'.format(name=instructor.full_name()) self._errors['instructors'] = self.error_class([error_msg]) raise forms.ValidationError('Ineligible exam') course_instance = CourseInstance.objects.annotate( count=Count('instructors')).filter(count=len( self.exam_instructors), term=term, course=course) for instructor in self.exam_instructors: course_instance = course_instance.filter(instructors=instructor) if course_instance.exists(): course_instance = course_instance.get() else: course_instance = CourseInstance.objects.create(term=term, course=course) course_instance.instructors.add(*self.exam_instructors) course_instance.save() self.course_instance = course_instance
def assign_event_type_achievements(instance, type_events): # obtain the user's attendance for events with the same type as instance type_attendance = EventAttendance.objects.filter( user=instance.user, event__event_type=instance.event.event_type, event__term=instance.event.term, event__cancelled=False) event_type = instance.event.event_type # a map from the name of the event_type to the name of the corresponding # achievement, for use in determining what achievement to update event_type_map = { 'Meeting': 'meetings', 'Big Social': 'big_socials', 'Bent Polishing': 'bent_polishings', 'Infosession': 'infosessions', 'Community Service': 'service', 'E Futures': 'efutures', 'Fun': 'fun', 'Professional Development': 'prodev' } if event_type.name in event_type_map: short_name = 'attend_all_{}'.format( event_type_map[instance.event.event_type.name]) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement and (type_events.count() == type_attendance.count()): achievement.assign(instance.user, term=instance.event.term)
def test_student_org_user_profile_post_save(self): """Tests whether creating and saving a StudentOrgUserProfile properly ensures that a CollegeStudentInfo object exists for the user in the post_save callback. """ self.assertIsNotNone( get_object_or_none(CollegeStudentInfo, user=self.user))
def assign_event_type_achievements(instance, type_events): # obtain the user's attendance for events with the same type as instance type_attendance = EventAttendance.objects.filter( user=instance.user, event__event_type=instance.event.event_type, event__term=instance.event.term, event__cancelled=False) event_type = instance.event.event_type # a map from the name of the event_type to the name of the corresponding # achievement, for use in determining what achievement to update event_type_map = { 'Meeting': 'meetings', 'Big Social': 'big_socials', 'Bent Polishing': 'bent_polishings', 'Infosession': 'infosessions', 'Community Service': 'service', 'E Futures': 'efutures', 'Fun': 'fun', 'Professional Development': 'prodev' } if event_type.name in event_type_map: short_name = 'attend_all_{}'.format( event_type_map[instance.event.event_type.name]) achievement = get_object_or_none( Achievement, short_name=short_name) if achievement and (type_events.count() == type_attendance.count()): achievement.assign(instance.user, term=instance.event.term)
def get_context_data(self, **kwargs): context = super(ResumeEditView, self).get_context_data(**kwargs) if self.resume: context['resume'] = self.resume context['info'] = get_object_or_none(CollegeStudentInfo, user=self.request.user) return context
def get_context_data(self, **kwargs): context = super(ResumeEditView, self).get_context_data(**kwargs) if self.resume: context['resume'] = self.resume context['info'] = get_object_or_none( CollegeStudentInfo, user=self.request.user) return context
def assign_completion_achievements(sender, instance, created, **kwargs): if instance.achievement.short_name != 'acquire_15_achievements': # count the number of acquired achievements for the user user_achievements = UserAchievement.objects.select_related( 'term').filter(user=instance.user, acquired=True).order_by('term__pk') achievement_count = user_achievements.count() # the number of acquired achievements to obtain these achievements benchmarks = [15] for benchmark in benchmarks: short_name = 'acquire_{:02d}_achievements'.format(benchmark) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement: if achievement_count < benchmark: achievement.assign(instance.user, acquired=False, progress=achievement_count) else: achievement.assign(instance.user, term=user_achievements[benchmark - 1].term)
def get_context_data(self, **kwargs): context = super(HouseMembersEditView, self).get_context_data( **kwargs) context['houses'] = House.objects.all() # Find house leaders and candidates to check groups without querying DB house_leader = get_object_or_none(OfficerPosition, short_name='house-leaders') context['house_leaders'] = get_user_model().objects.filter( officer__term=self.display_term, officer__position=house_leader) context['candidates'] = get_user_model().objects.filter( candidate__term=self.display_term) # Create a dict with user ids as keys mapping to house names to identify # users who are already members of a house. house_members = HouseMember.objects.filter( user__in=context['eligible_house_members'], term=self.display_term).select_related('house', 'user') user_house_dict = {} for member in house_members: user_house_dict[member.user.id] = member.house.mailing_list context['user_houses'] = user_house_dict return context
def save(self, *args, **kwargs): """Check if professors are blacklisted.""" for instructor in self.syllabus_instructors: permission = get_object_or_none(InstructorSyllabusPermission, instructor=instructor) if permission and permission.permission_allowed is False: self.instance.blacklisted = True return super(UploadForm, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """Check if professors are blacklisted.""" for instructor in self.exam_instructors: permission = get_object_or_none( InstructorPermission, instructor=instructor) if permission and permission.permission_allowed is False: self.instance.blacklisted = True return super(UploadForm, self).save(*args, **kwargs)
def handle(self, *args, **options): # exclude reports from just today or reports that can't possibly be in # the current academic year last_year = Term.objects.get_current_term().year - 1 unfinished_reports = ProjectReport.objects.filter( complete=False, term__year__gte=last_year, date__lt=timezone.localtime(timezone.now()).date()) reports_by_committee = {} for report in unfinished_reports: committee = report.committee if committee not in reports_by_committee: reports_by_committee[committee] = [] reports_by_committee[committee].append(report) from_emails = [] for from_email in ProjectReportFromEmail.objects.all(): email_str = '"{}" <{}@{}>'.format( from_email.name, from_email.email_prefix, HOSTNAME) from_emails.append(email_str) random.shuffle(from_emails) rsec = get_object_or_none(Officer, term=Term.objects.get_current_term(), position__short_name='rsec') rsec_mailing_list = OfficerPosition.objects.get( short_name='rsec').mailing_list if rsec: signature_lines = [rsec.user.userprofile.get_common_name(), 'Recording Secretary'] else: signature_lines = ['IT Committee'] for i, committee in enumerate(reports_by_committee.keys()): reports = reports_by_committee[committee] context = {'committee': committee.long_name, 'reports': reports, 'signature_lines': signature_lines} subject_format = '[TBP] {} Project Report Reminders as of {:%m/%d}' complete_message = EmailMultiAlternatives( subject=subject_format.format( committee.long_name, timezone.localtime(timezone.now())), body=render_to_string('project_reports/email_reminder.txt', context), from_email=from_emails[i % len(from_emails)], to=list(set(['{}@{}'.format(report.author.username, HOSTNAME) for report in reports])), cc=['{}@{}'.format(committee.mailing_list, HOSTNAME), '{}@{}'.format(rsec_mailing_list, HOSTNAME)], headers={'Reply-to': '{}@{}'.format( rsec_mailing_list, HOSTNAME)}) complete_message.attach_alternative(render_to_string( 'project_reports/email_reminder.html', context), 'text/html') complete_message.content_subtype = 'html' complete_message.send()
def __init__(self, *args, **kwargs): super(InstructorEditForm, self).__init__(*args, **kwargs) self.permission = get_object_or_none( InstructorPermission, instructor=self.instance) if self.permission: self.fields['permission_allowed'].initial = ( self.permission.permission_allowed) self.fields['correspondence'].initial = ( self.permission.correspondence)
def __init__(self, *args, **kwargs): super(InstructorEditForm, self).__init__(*args, **kwargs) self.permission = get_object_or_none(InstructorPermission, instructor=self.instance) if self.permission: self.fields['permission_allowed'].initial = ( self.permission.permission_allowed) self.fields['correspondence'].initial = ( self.permission.correspondence)
def assign_house(request): """Assign an officer or candidate to a house for the current semester. The user is specified by a userPK post parameter, the house is specified by a houseName post parameter, and the term is specified by a term post parameter which is the url name of the display term. """ user_pk = request.POST.get('userPK') user = get_user_model().objects.get(pk=user_pk) house_name = request.POST.get('houseName') house = House.objects.get(mailing_list=house_name) term = Term.objects.get_by_url_name(request.POST.get('term')) house_member, created = HouseMember.objects.get_or_create( user=user, term=term, defaults={'house': house}) # Find out if the user is a house leader for setting is_leader correctly user_house_leader = get_object_or_none( Officer, position__short_name='house-leaders', user__id=user_pk, term=term) if user_house_leader is not None: # Find out if there is already a house leader for this house existing_house_leader = get_object_or_none( HouseMember, house=house, is_leader=True, term=term) if existing_house_leader is not None: # If there is already a house leader in that house and we're trying # to add a house leader, delete any newly created HouseMember object # and return a 400 error to be handled by jQuery if created: house_member.delete() return json_response(status=400) else: house_member.is_leader = True # If an object was gotten, the user was in a different house previously if not created: house_member.house = house house_member.save() return json_response()
def dispatch(self, request, *args, **kwargs): house_pk = request.GET.get('house', '') if house_pk: self.display_house = get_object_or_none(House, id=house_pk) if self.display_house is None: # Bad request return render(request, template_name='400.html', status=400) return super(CandidateProgressMixin, self).dispatch(request, *args, **kwargs)
def test_cancel_event_pr_save(self): """ Ensure an event is cancelled but the project report is saved.""" event_name_pr_save = 'My Event With a PR to Save' c_form = self.setup_cancel_event( extra_fields={'name': event_name_pr_save, 'needs_pr': True}, delete_pr=False) event = get_object_or_none(Event, name=event_name_pr_save) c_form.event = event self.assertTrue(c_form.is_valid()) self.assertIsNotNone(event.project_report) self.assertTrue(event.cancelled)
def dispatch(self, request, *args, **kwargs): req_pk = request.GET.get('req', '') if req_pk: self.display_req = get_object_or_none(CandidateRequirement, id=req_pk) if self.display_req is None: # Bad request return render(request, template_name='400.html', status=400) return super(CandidateProgressByReqView, self).dispatch(request, *args, **kwargs)
def achievement_notification_delete(sender, instance, **kwargs): """Delete the notification if it exists for the user achievement if it is deleted. """ notification = get_object_or_none( Notification, user=instance.user, content_type=ContentType.objects.get_for_model(UserAchievement), object_pk=instance.pk) if notification: notification.delete()
def project_report_notification_delete(sender, instance, **kwargs): """Delete the notification if it exists for the project report when it is deleted. """ notification = get_object_or_none( Notification, user=instance.author, content_type=ContentType.objects.get_for_model(ProjectReport), object_pk=instance.pk) if notification: notification.delete()
def assign_procrastination_achievement(instance): # obtain the time taken to write the project report (the date between # the event date and the first completed date) event_date = instance.date completion_date = instance.first_completed_at.date() writing_time = completion_date - event_date if writing_time.days >= 60: achievement = get_object_or_none( Achievement, short_name='project_report_procrastination') if achievement: achievement.assign(instance.author, term=instance.term)
def test_cancel_event_no_pr(self): """ Ensure that a simple event with no project report is cancelled.""" event_name_no_pr = 'My Event Without a PR' c_form = self.setup_cancel_event( extra_fields={'name': event_name_no_pr}, delete_pr=False) event = get_object_or_none(Event, name=event_name_no_pr) self.assertIsNone(event.project_report) c_form.event = event # Call is_valid to put cleaned data for the test. self.assertTrue(c_form.is_valid()) self.assertTrue(event.cancelled)
def clean(self): """Check the signup limit has not been exceeded.""" # pylint: disable=w0201 cleaned_data = super(EventSignUpForm, self).clean() num_guests = cleaned_data.get('num_guests') num_rsvps = self.event.get_num_rsvps() # Get the previous signup if it exists if self.user.is_authenticated(): signup = get_object_or_none(EventSignUp, event=self.event, user=self.user) else: signup = get_object_or_none(EventSignUp, event=self.event, email=cleaned_data.get('email')) # If the user has signed up previously and not unsigned up, subtract # the user and the number of guests from the total number of rsvps if signup and not signup.unsignup: num_rsvps -= (1 + signup.num_guests) # Add the user and the number of guests to the total number of rsvps # and check that it is less than the signup limit if the limit is not # zero (a limit of zero implies unlimited signups) if self.event.signup_limit != 0: if (1 + num_guests + num_rsvps) > self.event.signup_limit: raise forms.ValidationError('There are not enough spots left.') # Only save a new object if a signup does not already exist for this # user. Otherwise, just update the existing object. if signup: self.instance = signup self.instance.event = self.event self.instance.unsignup = False if self.user.is_authenticated(): self.instance.user = self.user return cleaned_data
def project_report_notification(sender, instance, created, **kwargs): """Clear the notification if it exists for the project report when it is completed. """ if instance.complete: notification = get_object_or_none( Notification, user=instance.author, content_type=ContentType.objects.get_for_model(ProjectReport), object_pk=instance.pk) if notification: notification.cleared = True notification.save()
def assign_diffposition_achievements(instance, committee_terms): three_unique_positions = get_object_or_none( Achievement, short_name='three_unique_positions') if len(committee_terms) >= 3: # terms is a list of lists terms = committee_terms.values() if three_unique_positions: # find the first semester that this person was on their third # different committee third_committee_terms = terms[2] three_unique_positions.assign(instance.user, term=third_committee_terms[0])
def assign_tenure_achievements(instance, unique_terms): num_unique_terms = len(unique_terms) # 1 to 8 officer semesters for i in range(1, 9): short_name = 'officersemester{:02d}'.format(i) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement: if num_unique_terms < i: achievement.assign( instance.user, acquired=False, progress=num_unique_terms) else: achievement.assign(instance.user, term=unique_terms[i-1])
def assign_diffposition_achievements(instance, committee_terms): three_unique_positions = get_object_or_none( Achievement, short_name='three_unique_positions') if len(committee_terms) >= 3: # terms is a list of lists terms = committee_terms.values() if three_unique_positions: # find the first semester that this person was on their third # different committee third_committee_terms = terms[2] three_unique_positions.assign( instance.user, term=third_committee_terms[0])
def test_cancel_event_no_pr_del(self): """ Event cancellation should proceed smoothly if a delete is request with no project report. """ event_name_no_pr_del = 'My Event Without a PR, Try Delete' c_form = self.setup_cancel_event( extra_fields={'name': event_name_no_pr_del}, delete_pr=True) event = get_object_or_none(Event, name=event_name_no_pr_del) self.assertIsNone(event.project_report) c_form.event = event self.assertTrue(c_form.is_valid()) self.assertTrue(event.cancelled)
def assign_tenure_achievements(instance, unique_terms): num_unique_terms = len(unique_terms) # 1 to 8 officer semesters for i in range(1, 9): short_name = 'officersemester{:02d}'.format(i) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement: if num_unique_terms < i: achievement.assign(instance.user, acquired=False, progress=num_unique_terms) else: achievement.assign(instance.user, term=unique_terms[i - 1])
def clean(self): """Check the signup limit has not been exceeded.""" # pylint: disable=w0201 cleaned_data = super(EventSignUpForm, self).clean() num_guests = cleaned_data.get('num_guests') num_rsvps = self.event.get_num_rsvps() # Get the previous signup if it exists if self.user.is_authenticated(): signup = get_object_or_none( EventSignUp, event=self.event, user=self.user) else: signup = get_object_or_none( EventSignUp, event=self.event, email=cleaned_data.get('email')) # If the user has signed up previously and not unsigned up, subtract # the user and the number of guests from the total number of rsvps if signup and not signup.unsignup: num_rsvps -= (1 + signup.num_guests) # Add the user and the number of guests to the total number of rsvps # and check that it is less than the signup limit if the limit is not # zero (a limit of zero implies unlimited signups) if self.event.signup_limit != 0: if (1 + num_guests + num_rsvps) > self.event.signup_limit: raise forms.ValidationError('There are not enough spots left.') # Only save a new object if a signup does not already exist for this # user. Otherwise, just update the existing object. if signup: self.instance = signup self.instance.event = self.event self.instance.unsignup = False if self.user.is_authenticated(): self.instance.user = self.user return cleaned_data
def assign_alphabet_pr_achievement(instance): # see if letters A-Z are in project report text project_report_text = ''.join([ instance.title, instance.other_group, instance.description, instance.purpose, instance.organization, instance.cost, instance.problems, instance.results ]) unused_letters = set(string.lowercase) unused_letters.difference_update(project_report_text.lower()) if len(unused_letters) == 0: achievement = get_object_or_none(Achievement, short_name='alphabet_project_report') if achievement: achievement.assign(instance.author, term=instance.term)
def assign_lifetime_achievements(instance, total_attendance): attendance_count = total_attendance.count() # the number of events needed to get achievements benchmarks = [25, 50, 78, 100, 150, 200, 300] for benchmark in benchmarks: short_name = 'attend{:03d}events'.format(benchmark) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement: if attendance_count < benchmark: achievement.assign( instance.user, acquired=False, progress=attendance_count) else: achievement.assign( instance.user, term=total_attendance[benchmark - 1].event.term)
def assign_alphabet_pr_achievement(instance): # see if letters A-Z are in project report text project_report_text = ''.join([instance.title, instance.other_group, instance.description, instance.purpose, instance.organization, instance.cost, instance.problems, instance.results]) unused_letters = set(string.lowercase) unused_letters.difference_update(project_report_text.lower()) if len(unused_letters) == 0: achievement = get_object_or_none(Achievement, short_name='alphabet_project_report') if achievement: achievement.assign(instance.author, term=instance.term)
def assign_lifetime_exam_achievements(instance): # obtain all approved exams submitted by user approved_exams = Exam.objects.get_approved().filter( submitter=instance.submitter) approved_exam_count = approved_exams.count() # the number of submitted exams needed to get achievements benchmarks = [5, 10, 25, 50] for benchmark in benchmarks: short_name = 'upload_{:02d}_exams'.format(benchmark) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement: if approved_exam_count < benchmark: achievement.assign( instance.submitter, acquired=False, progress=approved_exam_count) else: achievement.assign(instance.submitter)
def import_exam_flags(): models = get_json_data('examfiles.examflag.json') for model in models: fields = model['fields'] # Don't import flags for exams that weren't imported because they were # duplicates with a different file type exam = get_object_or_none(Exam, pk=fields['exam']) if not exam: continue exam_flag, _ = ExamFlag.objects.get_or_create( pk=model['pk'], exam=exam, reason=fields['reason']) # Convert the naive datetime into an aware datetime created = parser.parse(fields['created']) exam_flag.created = make_aware(created, timezone) exam_flag.save()
def update_candidate_initiation_status(request): """Endpoint for updating a candidate's initiation status. The post parameters "candidate" and "initiated" specify the candidate (by Candidate pk) and their new initiation status, respectively. """ candidate_pk = request.POST.get('candidate') if not candidate_pk: return json_response(status=404) candidate = get_object_or_none(Candidate, pk=candidate_pk) initiated = json.loads(request.POST.get('initiated')) if not candidate or initiated is None: return json_response(status=400) candidate.initiated = initiated candidate.save(update_fields=['initiated']) # TODO(sjdemartini): Update LDAP-related information, like removal from # or addition to relevant groups. # TODO(sjdemartini): Update relevant mailing lists, moving initiated # candidates off of the candidates list and onto the members list. return json_response()
def set_course_instance(self, cleaned_data): """Check if a course is valid and whether a course instance exists with the exact instructors given, and create a course instance if one doesn't exist. """ department = self.cleaned_data.get('department') course_number = self.cleaned_data.get('course_number') term = self.cleaned_data.get('term') course = get_object_or_none( Course, department=department, number=course_number) if not course: error_msg = '{department} {number} does not exist.'.format( department=department, number=course_number) self._errors['department'] = self.error_class([error_msg]) self._errors['course_number'] = self.error_class([error_msg]) raise forms.ValidationError('Invalid course') # check instructors to prevent trying to iterate over nothing self.exam_instructors = self.cleaned_data.get('instructors') if not self.exam_instructors: raise forms.ValidationError('Please fill out all fields.') course_instance = CourseInstance.objects.annotate( count=Count('instructors')).filter( count=len(self.exam_instructors), term=term, course=course) for instructor in self.exam_instructors: course_instance = course_instance.filter(instructors=instructor) if course_instance.exists(): course_instance = course_instance.get() else: course_instance = CourseInstance.objects.create( term=term, course=course) course_instance.instructors.add(*self.exam_instructors) course_instance.save() self.course_instance = course_instance
def assign_lifetime_pr_achievements(instance): # obtain all project reports authored by user project_reports = ProjectReport.objects.select_related( 'event__term').filter( author=instance.author, complete=True).order_by('event__term__pk') project_report_count = project_reports.count() # the number of project reports needed to get achievements benchmarks = [1, 5, 15] for benchmark in benchmarks: short_name = 'write_{:02d}_project_reports'.format(benchmark) achievement = get_object_or_none(Achievement, short_name=short_name) if achievement: if project_report_count < benchmark: achievement.assign( instance.author, acquired=False, progress=project_report_count) else: achievement.assign( instance.author, term=project_reports[benchmark - 1].term)
def assign_alphabet_achievement(instance, remaining_letters): if len(remaining_letters) == 0: achievement = get_object_or_none(Achievement, short_name='alphabet_attendance') if achievement: achievement.assign(instance.user, term=instance.event.term)
def assign_salad_bowl_achievement(instance, types_attended, types_existing): if types_attended.count() == types_existing.count(): achievement = get_object_or_none( Achievement, short_name='attend_each_type') if achievement: achievement.assign(instance.user, term=instance.event.term)
def assign_straight_to_the_top_achievement(instance, straight_to_the_top_term): straighttothetop = get_object_or_none( Achievement, short_name='straighttothetop') if straighttothetop: straighttothetop.assign(instance.user, term=straight_to_the_top_term)
def dispatch(self, *args, **kwargs): self.resume = get_object_or_none(Resume, user=self.request.user) return super(ResumeEditView, self).dispatch(*args, **kwargs)
def test_student_org_user_profile_post_save(self): """Tests whether creating and saving a StudentOrgUserProfile properly ensures that a CollegeStudentInfo object exists for the user in the post_save callback. """ self.assertIsNotNone(get_object_or_none(CollegeStudentInfo, user=self.user))