def isCompleted(self): """ This step is completed if the student has marked their application as complete or answered questions for all of their classes. I know this is slow sometimes. -Michael P""" app = get_current_request().user.getApplication(self.program) # Check if the application is empty or marked as completed. if app.done: return True app.set_questions() if app.questions.all().count() == 0: return True # Code below here may be unnecessary; it's just to save students the trouble # of clicking through to mark their application complete before they can confirm. # Get the student's responses to application questions. responses = app.responses.all() response_question_ids = [x.question.id for x in responses] response_dict = {} for i in range(len(responses)): response_dict[response_question_ids[i]] = responses[i] # Check that they responded to everything. classes = get_current_request().user.getAppliedClasses(self.program) for cls in classes: for i in [x['id'] for x in cls.studentappquestion_set.all().values('id')]: if i not in response_question_ids: return False elif (not response_dict[i].complete) and len(response_dict[i].response) == 0: return False return True
def isCompleted(self): return Record.user_completed( user=get_current_request().user, event="med", program=self.program) \ or Record.user_completed( user=get_current_request().user, event="med_bypass", program=self.program)
def isCompleted(self): if module_ext.RemoteProfile.objects.filter( user=get_current_request().user, program=self.program).exists(): return True else: regProf, created = module_ext.RemoteProfile.objects.get_or_create( user=get_current_request().user, program=self.program) return False
def isCompleted(self): """ Whether the user has paid for this program or its parent program. """ if (len( Document.get_completed(get_current_request().user, self.program_anchor_cached())) > 0): return True else: parent_program = self.program.getParentProgram() if parent_program is not None: return (len( Document.get_completed(get_current_request().user, parent_program.anchor)) > 0) return False
def get_handouts(self): sections = get_current_request().user.getTaughtSections(self.program) sections = filter(lambda x: x.isAccepted() and x.meeting_times.count() > 0, sections) if len(sections) > 0: return {'teacherschedule': 'Your Class Schedule', 'classroster': 'Class Rosters'} else: return {}
def prepare(self, context): clrmi = module_ext.ClassRegModuleInfo.objects.get( module__program=self.program) context['num_teacher_questions'] = clrmi.num_teacher_questions context['classes'] = get_current_request().user.getTaughtClasses( ).filter(parent_program=self.program) return context
def deadline_met(self): if get_current_request().user.isAdmin(self.program): return True tmpModule = ProgramModuleObj() tmpModule.__dict__ = self.__dict__ return tmpModule.deadline_met()
def deadline_met(self, extension=''): # Short-circuit the request middleware during testing, when we call # this function without an actual request. if hasattr(self, 'user'): user = self.user else: request = get_current_request() user = request.user if not user or not self.program: raise ESPError(False), "There is no user or program object!" if self.module.module_type != 'learn' and self.module.module_type != 'teach': return True canView = user.isOnsite(self.program) or user.isAdministrator( self.program) if not canView: deadline = { 'learn': 'Student', 'teach': 'Teacher' }[self.module.module_type] + extension canView = Permission.user_has_perm(user, deadline, program=self.program) return canView
def getCoreView(self, tl): import esp.program.modules.models modules = self.program.getModules(get_current_request().user, tl) for module in modules: if isinstance(module, CoreModule): return getattr(module, module.get_main_view(tl)) assert False, 'No core module to return to!'
def getCoreURL(self, tl): import esp.program.modules.models modules = self.program.getModules(get_current_request().user, tl) for module in modules: if isinstance(module, CoreModule): return '/' + tl + '/' + self.program.getUrlBase( ) + '/' + module.get_main_view(tl)
def isCompleted(self): """ Return true iff user has signed up for everything possible. If there are teacher training timeslots, requires signing up for them. If there are teacher interview timeslots, requires those too. """ entries = self.entriesByTeacher(get_current_request().user) return (self.getTimes('interview').count() == 0 or entries['interview'].count() > 0) and (self.getTimes('training').count() == 0 or entries['training'].count() > 0)
def isCompleted(self): """ Return true iff user has signed up for everything possible. If there are teacher training timeslots, requires signing up for them. If there are teacher interview timeslots, requires those too. """ bits = self.bitsByTeacher(get_current_request().user) return (self.getTimes('interview').count() == 0 or bits['interview'].count() > 0) and (self.getTimes('training').count() == 0 or bits['training'].count() > 0)
def prepare(self, context): context['textmessage_form'] = TextMessageForm() profile = RegistrationProfile.getLastForProgram(get_current_request().user, self.program) if profile.text_reminder is True: if profile.contact_user: context['textmessage_form'] = TextMessageForm(initial={'phone_number': profile.contact_user.phone_cell}) return context
def save(self, *args, **kwargs): # Overridden to populate created_by and modified_by. I'm not crazy about this method as it mixes models and requests, but I think it's worth it to save having to pass it around manually everywhere the thing gets touched. Note that the creation and modification times already get autocreated by django. If you're saving ClassFlags outside of a request somehow, make sure you manually populate this stuff. request = get_current_request() if request is not None: self.modified_by = request.user if self.id is None: #We are creating, rather than modifying, so we don't yet have an id. self.created_by = request.user super(ClassFlag, self).save(*args, **kwargs)
def verify_email(self): import string import random from esp.users.models import PersistentQueryFilter from esp.dbmail.models import MessageRequest from django.template import loader symbols = string.ascii_uppercase + string.digits code = "".join([random.choice(symbols) for x in range(30)]) regProf = RegistrationProfile.getLastForProgram( get_current_request().user, self.program) if regProf.email_verified: return self.goToCore(tl) if request.method == 'POST' and request.POST.has_key('verify_me'): # create the variable modules variable_modules = { 'program': self.program, 'user': get_current_request().user } # get the filter object filterobj = PersistentQueryFilter.getFilterFromQ( Q(id=get_current_request().user.id), User, 'User %s' % get_current_request().user.username) newmsg_request = MessageRequest.createRequest( var_dict=variable_modules, subject='[ESP] Email Verification For esp.mit.edu', recipients=filterobj, sender='"MIT Educational Studies Program" <*****@*****.**>', creator=self, msgtext=loader.find_template_source('email/verify')[0]) newmsg_request.save() return render_to_response(self.baseDir() + 'emailsent.html', request, {}) return render_to_response(self.baseDir() + 'sendemail.html', request, {})
def deadline_met(self, extension=''): if get_current_request().user.isAdmin(self.program): return True if len(extension) > 0: return super(TeacherClassRegModule, self).deadline_met(extension) tmpModule = ProgramModuleObj() tmpModule.__dict__ = self.__dict__ return tmpModule.deadline_met( '/Classes/Create') or tmpModule.deadline_met('/Classes/Edit')
def isCompleted(self): """ Make sure that they have indicated sufficient availability for all classes they have signed up to teach. """ available_slots = get_current_request().user.getAvailableTimes(self.program, ignore_classes=True) # Check number of timeslots against Tag-specified minimum if Tag.getTag('min_available_timeslots'): min_ts_count = int(Tag.getTag('min_available_timeslots')) if len(available_slots) < min_ts_count: return False # Round durations of both classes and timeslots to nearest 30 minutes total_time = get_current_request().user.getTaughtTime(self.program, include_scheduled=True, round_to=0.5) available_time = timedelta() for a in available_slots: available_time = available_time + timedelta( seconds = 1800 * round( a.duration().seconds / 1800.0 ) ) if (total_time > available_time) or (available_time == timedelta()): return False else: return True
def prepare(self, context={}): context['splashinfo'] = SplashInfo.getForUser(get_current_request().user, self.program) if not Tag.getBooleanTag('splashinfo_siblingdiscount', default=True): context['splashinfo'].include_siblingdiscount = False else: context['splashinfo'].include_siblingdiscount = True context['splashinfo'].include_lunchsat = Tag.getBooleanTag('splashinfo_lunchsat', default=True) context['splashinfo'].include_lunchsun = Tag.getBooleanTag('splashinfo_lunchsun', default=True) return context
def __init__(self, *args, **kwargs): super(ConfigForm, self).__init__(*args, **kwargs) # fill in %(host)s for front_page_style.help_text request = get_current_request() if request is not None and 'HTTP_HOST' in request.META: host = request.META['HTTP_HOST'] else: host = settings.SITE_INFO[1] self.fields['front_page_style'].help_text = \ self.fields['front_page_style'].help_text % \ {'home': '/', 'host': host}
def deadline_met(self, extension=''): from esp.users.models import UserBit from esp.datatree.models import GetNode, DataTree if not get_current_request().user or not self.program: raise ESPError(False), "There is no user or program object!" if self.module.module_type != 'learn' and self.module.module_type != 'teach': return True canView = get_current_request().user.isOnsite(self.program) if not canView: test_node = GetNode('V/Deadline/Registration/' + { 'learn': 'Student', 'teach': 'Teacher' }[self.module.module_type] + extension) canView = UserBit.UserHasPerms(get_current_request().user, self.program.anchor_id, test_node) return canView
def prepare(self, context={}): """ prepare returns the context for the main teacherreg page. """ context['can_edit'] = self.deadline_met('/Classes/Edit') context['can_create'] = self.any_reg_is_open() context['can_create_class'] = self.class_reg_is_open() context['can_create_open_class'] = self.open_class_reg_is_open() context['crmi'] = self.crmi context['clslist'] = self.clslist(get_current_request().user) context['friendly_times_with_date'] = Tag.getBooleanTag( 'friendly_times_with_date', self.program, False) context[ 'open_class_category'] = self.program.open_class_category.category return context
def prepare(self, context={}): """ prepare returns the context for the main teacherreg page. This will just set the teacherclsmodule as this module, since everything else can be gotten from hooks. """ context['can_edit'] = self.deadline_met('/Classes/Edit') context['can_create'] = self.deadline_met('/Classes/Create') context['teacherclsmodule'] = self # ... context['clslist'] = self.clslist(get_current_request().user) context['friendly_times_with_date'] = (Tag.getProgramTag( key='friendly_times_with_date', program=self.program, default=False) == "True") context['allow_class_import'] = 'false' not in Tag.getTag( 'allow_class_import', default='true').lower() return context
def __init__(self, module, *args, **kwargs): super(TeacherEventSignupForm, self).__init__(*args, **kwargs) self.module = module self.user = get_current_request().user interview_times = module.getTimes('interview') if interview_times.count() > 0: self.fields['interview'].choices = [ (x.id, x.description) for x in interview_times if self._slot_is_available(x) ] else: self.fields['interview'].widget = forms.HiddenInput() training_times = module.getTimes('training') if training_times.count() > 0: self.fields['training'].choices = [ (x.id, x.description) for x in training_times if not self._slot_too_late(x) ] else: self.fields['training'].widget = forms.HiddenInput()
def deadline_met(self, extension=''): # Short-circuit the request middleware during testing, when we call # this function without an actual request. if hasattr(self, 'user'): user = self.user else: request = get_current_request() user = request.user if not user or not self.program: raise ESPError(False), "There is no user or program object!" if self.module.module_type != 'learn' and self.module.module_type != 'teach': return True canView = user.isOnsite(self.program) or user.isAdministrator(self.program) if not canView: deadline = {'learn':'Student', 'teach':'Teacher'}[self.module.module_type]+extension canView = Permission.user_has_perm(user, deadline, program=self.program) return canView
def getClassFromId(self, clsid, tl='teach'): """ This function can be called from a view to get a class object from an id. The id can be given with request or extra, but it will try to get it in any way. """ from esp.program.models import ClassSubject classes = [] try: clsid = int(clsid) except: return (False, True) classes = ClassSubject.objects.filter(id = clsid) if len(classes) == 1: if not get_current_request().user.canEdit(classes[0]): from esp.middleware import ESPError raise ESPError(False), 'You do not have permission to edit %s.' %\ classes[0].title() else: Found = True return (classes[0], True) return (False, False)
def noclasses(self): """ Returns true of there are no classes in this program """ return len(self.clslist(get_current_request().user)) < 1
def isCompleted(self): """Return true if user has filled out the teacher quiz.""" return UserBit.valid_objects().filter(user=get_current_request().user, qsc=self.program.anchor, verb=self.reg_verb).exists()
def isCompleted(self): return StudentRegistration.valid_objects().filter(user=get_current_request().user, relationship__name="Request").exists()
def isCompleted(self): regProf = RegistrationProfile.getLastForProgram(get_current_request().user, self.program) return regProf.id is not None
def isCompleted(self): return Record.objects.filter(user=get_current_request().user, program=self.program, event=self.event).exists()
def have_paid(self): iac = IndividualAccountingController(self.program, get_current_request().user) return (iac.amount_due() <= 0)
def extracosts(self,request, tl, one, two, module, extra, prog): """ Query the user for any extra items they may wish to purchase for this program This module should ultimately deal with things like optional lab fees, etc. Right now it doesn't. """ if self.have_paid(): raise ESPError("You've already paid for this program. Please make any further changes on-site so that we can charge or refund you properly.", log=False) # Determine which line item types we will be asking about iac = IndividualAccountingController(self.program, get_current_request().user) costs_list = iac.get_lineitemtypes(optional_only=True).filter(max_quantity__lte=1, lineitemoptions__isnull=True) multicosts_list = iac.get_lineitemtypes(optional_only=True).filter(max_quantity__gt=1, lineitemoptions__isnull=True) multiselect_list = iac.get_lineitemtypes(optional_only=True).filter(lineitemoptions__isnull=False) # Fetch the user's current preferences prefs = iac.get_preferences() forms_all_valid = True ## Another dirty hack, left as an exercise to the reader if request.method == 'POST': # Initialize a list of forms using the POST data costs_db = [ { 'LineItemType': x, 'CostChoice': CostItem(request.POST, prefix="%s" % x.id) } for x in costs_list ] + \ [ x for x in \ [ { 'LineItemType': x, 'CostChoice': MultiCostItem(request.POST, prefix="%s" % x.id) } for x in multicosts_list ] \ if x['CostChoice'].is_valid() and 'cost' in x['CostChoice'].cleaned_data ] + \ [ { 'LineItemType': x, 'CostChoice': MultiSelectCostItem(request.POST, prefix="multi%s" % x.id, choices=x.option_choices, required=(x.required)) } for x in multiselect_list ] # Get a list of the (line item, quantity) pairs stored in the forms # as well as a list of line items which had invalid forms form_prefs = [] preserve_items = [] for item in costs_db: form = item['CostChoice'] lineitem_type = item['LineItemType'] if form.is_valid(): if isinstance(form, CostItem): if form.cleaned_data['cost'] is True: form_prefs.append((lineitem_type.text, 1, lineitem_type.amount, None)) elif isinstance(form, MultiCostItem): if form.cleaned_data['cost'] is True: form_prefs.append((lineitem_type.text, form.cleaned_data['count'], lineitem_type.amount, None)) elif isinstance(form, MultiSelectCostItem): if form.cleaned_data['option']: form_prefs.append((lineitem_type.text, 1, None, int(form.cleaned_data['option']))) else: # Preserve selected quantity for any items that we don't have a valid form for preserve_items.append(lineitem_type.text) forms_all_valid = False # Merge previous and new preferences (update only if the form was valid) new_prefs = [] for lineitem_name in preserve_items: if lineitem_name in map(lambda x: x[0], prefs): new_prefs.append(prefs[map(lambda x: x[0], prefs).index(lineitem_name)]) new_prefs += form_prefs iac.apply_preferences(new_prefs) # Redirect to main student reg page if all data was recorded properly # (otherwise, the code below will reload the page) if forms_all_valid: bit, created = Record.objects.get_or_create(user=request.user, program=self.program, event=self.event) return self.goToCore(tl) count_map = {} for lineitem_type in iac.get_lineitemtypes(optional_only=True): count_map[lineitem_type.text] = [lineitem_type.id, 0, None, None] for item in iac.get_preferences(): for i in range(1, 4): count_map[item[0]][i] = item[i] forms = [ { 'form': CostItem( prefix="%s" % x.id, initial={'cost': (count_map[x.text][1] > 0) } ), 'LineItem': x } for x in costs_list ] + \ [ { 'form': MultiCostItem( prefix="%s" % x.id, initial={'cost': (count_map[x.text][1] > 0), 'count': count_map[x.text][1] } ), 'LineItem': x } for x in multicosts_list ] + \ [ { 'form': MultiSelectCostItem( prefix="multi%s" % x.id, initial={'option': count_map[x.text][3]}, choices=x.option_choices, required=(x.required)), 'LineItem': x } for x in multiselect_list ] return render_to_response(self.baseDir()+'extracosts.html', request, { 'errors': not forms_all_valid, 'forms': forms, 'financial_aid': request.user.hasFinancialAid(prog), 'select_qty': len(multicosts_list) > 0 })
def prepare(self, context={}): from esp.program.controllers.studentclassregmodule import RegistrationTypeController as RTC verbs = RTC.getVisibleRegistrationTypeNames(prog=self.program) regProf = RegistrationProfile.getLastForProgram(get_current_request().user, self.program) timeslots = self.program.getTimeSlots(types=['Class Time Block', 'Compulsory']) classList = ClassSection.prefetch_catalog_data(regProf.preregistered_classes(verbs=verbs)) prevTimeSlot = None blockCount = 0 user = get_current_request().user is_onsite = user.isOnsite(self.program) scrmi = self.program.studentclassregmoduleinfo # Filter out volunteer timeslots timeslots = [x for x in timeslots if x.event_type.description != 'Volunteer'] schedule = [] timeslot_dict = {} for sec in classList: # Get the verbs all the time in order for the schedule to show # the student's detailed enrollment status. (Performance hit, I know.) # - Michael P, 6/23/2009 # if scrmi.use_priority: sec.verbs = sec.getRegVerbs(user, allowed_verbs=verbs) sec.verb_names = [v.name for v in sec.verbs] sec.is_enrolled = True if "Enrolled" in sec.verb_names else False # While iterating through the meeting times for a section, # we use this variable to keep track of the first timeslot. # In the section_dict appended to timeslot_dict, # we save whether or not this is the first timeslot for this # section. If it isn't, the student schedule will indicate # this, and will not display the option to remove the # section. This is to prevent students from removing what # they have mistaken to be duplicated classes from their # schedules. first_meeting_time = True for mt in sec.get_meeting_times().order_by('start'): section_dict = {'section': sec, 'first_meeting_time': first_meeting_time} first_meeting_time = False if mt.id in timeslot_dict: timeslot_dict[mt.id].append(section_dict) else: timeslot_dict[mt.id] = [section_dict] for i in range(len(timeslots)): timeslot = timeslots[i] daybreak = False if prevTimeSlot != None: if not Event.contiguous(prevTimeSlot, timeslot): blockCount += 1 daybreak = True if timeslot.id in timeslot_dict: cls_list = timeslot_dict[timeslot.id] doesnt_have_enrollment = not any(sec['section'].is_enrolled for sec in cls_list) schedule.append((timeslot, cls_list, blockCount + 1, doesnt_have_enrollment)) else: schedule.append((timeslot, [], blockCount + 1, False)) prevTimeSlot = timeslot context['num_classes'] = len(classList) context['timeslots'] = schedule context['use_priority'] = scrmi.use_priority context['allow_removal'] = self.deadline_met('/Removal') return context
def isCompleted(self): return get_current_request().user.appliedFinancialAid(self.program)
def isCompleted(self): # TeacherBio.getLastForProgram() returns a new bio if one already exists. # So, mark this step completed if there is an existing (i.e. non-empty) bio. lastBio = TeacherBio.getLastForProgram(get_current_request().user, self.program) return ((lastBio.id is not None) and lastBio.bio and lastBio.slugbio)
def isCompleted(self): return Record.objects.filter(user=get_current_request().user, program=self.program, event="teacheracknowledgement").exists()
def isCompleted(self): return self.program.isConfirmed(get_current_request().user)
def isCompleted(self): return (len(get_current_request().user.getSectionsFromProgram( self.program)[:1]) > 0)
def isCompleted(self): """Whether the user made a decision about donating to LU.""" return Record.objects.filter(user=get_current_request().user, program=self.program, event=self.event).exists()
def isCompleted(self): return SplashInfo.hasForUser(get_current_request().user, self.program)
def getCoreURL(self, tl): import esp.program.modules.models modules = self.program.getModules(get_current_request().user, tl) for module in modules: if isinstance(module, CoreModule): return '/'+tl+'/'+self.program.getUrlBase()+'/'+module.get_main_view(tl)
def isCompleted(self): records = Record.objects.filter(user=get_current_request().user, event="twophase_reg_done", program=self.program) return records.count() != 0
def isCompleted(self): """ Whether the user has paid for this program or its parent program. """ return IndividualAccountingController(self.program, get_current_request().user).has_paid()
def isCompleted(self): """Return true if user has filled out the teacher quiz.""" return self.controller.isCompleted(get_current_request().user)
def isCompleted(self): return bool(StudentRegistration.valid_objects().filter(section__parent_class__parent_program=self.program, user=get_current_request().user))
def isCompleted(self): """Return true if user has filled out the teacher quiz.""" return Record.objects.filter(user=get_current_request().user, program=self.program, event=self.event).exists()
def isCompleted(self): return (len(get_current_request().user.getSectionsFromProgram(self.program)[:1]) > 0)
def prepare(self, context): clrmi = module_ext.ClassRegModuleInfo.objects.get(program=self.program) context['num_teacher_questions'] = clrmi.num_teacher_questions; context['classes'] = get_current_request().user.getTaughtClasses().filter(parent_program = self.program) return context
def runTest(self): from esp.program.models import RegistrationProfile # Check that the profile page does not cause an error when not logged in # (it should redirect to a login page) response = self.client.get('/learn/%s/profile' % self.program.getUrlBase()) self.assertEqual(response.status_code, 302) # Check that the people start out without profiles # We'll probably need to be a little more careful about how we set # the ProgramModuleObj's user if we ever cache isCompleted(). for student in self.students: get_current_request().user = student self.assertTrue( not self.moduleobj.isCompleted(), "The profile should be incomplete at first." ) # First student: Test copying of sufficiently recent profiles get_current_request().user = self.students[0] prof = self.students[0].getLastProfile() prof.program = None prof.save() self.assertTrue( self.students[0].registrationprofile_set.count() >= 1, "Profile failed to save." ) self.assertTrue( self.students[0].registrationprofile_set.count() <= 1, "Too many profiles." ) self.assertTrue( self.moduleobj.isCompleted(), "Profile failed to copy." ) self.assertTrue( self.students[0].registrationprofile_set.count() >= 2, "Copy failed to save." ) self.assertTrue( self.students[0].registrationprofile_set.count() <= 2, "Too many profiles." ) # Second student: Test non-auto-saving of sufficiently old profiles get_current_request().user = self.students[1] prof = self.students[1].getLastProfile() prof.program = None # HACK -- save properly to dump the appropriate cache. # Then save sneakily so that we can override the timestamp. prof.save() prof.last_ts = datetime.now() - timedelta(10) super(RegistrationProfile, prof).save() # Continue testing self.assertTrue( self.students[1].registrationprofile_set.count() >= 1, "Profile failed to save." ) self.assertTrue( self.students[1].registrationprofile_set.count() <= 1, "Too many profiles." ) self.assertTrue( not self.moduleobj.isCompleted(), "Profile too old but accepted anyway." ) self.assertTrue( self.students[1].registrationprofile_set.count() <= 1, "Too many profiles." ) get_current_request().user = self.students[2] for r in RegistrationProfile.objects.filter(user=self.students[2]): r.delete() # Test to see whether the graduation year is required self.client.login(username=self.students[2].username, password='******') response = self.client.post('%sprofile' % self.program.get_learn_url(), {'graduation_year': '', 'profile_page': ''}) lines = response.content.split('\n') ## Find the line for the start of the graduation-year form field for i, line in enumerate(lines): if '<select class="required" id="id_graduation_year" name="graduation_year">' in line: break self.assertTrue(i < len(lines)-1) ## Found the relevant line ## Find the line for the end of the graduation-year form field for j, line in enumerate(lines[i:]): if '</select>' in line: break self.assertTrue(j < len(lines) - 2) ## Found the line, need to also find the error message on the next line ## Find the error message self.assertTrue('<span class="form_error">This field is required.</span>' in lines[i+j+1]) ## Validate that the default value of the form is the empty string, like we assumed in POST'ing it above found_default = False for line in lines[i:i+j]: found_default = found_default or ('<option value="" selected="selected"></option>' in line) self.assertTrue(found_default)
def prepare(self, context={}): from esp.program.controllers.studentclassregmodule import RegistrationTypeController as RTC verbs = RTC.getVisibleRegistrationTypeNames(prog=self.program) regProf = RegistrationProfile.getLastForProgram( get_current_request().user, self.program) timeslots = self.program.getTimeSlots( types=['Class Time Block', 'Compulsory']) classList = ClassSection.prefetch_catalog_data( regProf.preregistered_classes(verbs=verbs)) prevTimeSlot = None blockCount = 0 user = get_current_request().user is_onsite = user.isOnsite(self.program) scrmi = self.program.studentclassregmoduleinfo # Filter out volunteer timeslots timeslots = [ x for x in timeslots if x.event_type.description != 'Volunteer' ] schedule = [] timeslot_dict = {} for sec in classList: # Get the verbs all the time in order for the schedule to show # the student's detailed enrollment status. (Performance hit, I know.) # - Michael P, 6/23/2009 # if scrmi.use_priority: sec.verbs = sec.getRegVerbs(user, allowed_verbs=verbs) sec.verb_names = [v.name for v in sec.verbs] sec.is_enrolled = True if "Enrolled" in sec.verb_names else False # While iterating through the meeting times for a section, # we use this variable to keep track of the first timeslot. # In the section_dict appended to timeslot_dict, # we save whether or not this is the first timeslot for this # section. If it isn't, the student schedule will indicate # this, and will not display the option to remove the # section. This is to prevent students from removing what # they have mistaken to be duplicated classes from their # schedules. first_meeting_time = True for mt in sec.get_meeting_times().order_by('start'): section_dict = { 'section': sec, 'first_meeting_time': first_meeting_time } first_meeting_time = False if mt.id in timeslot_dict: timeslot_dict[mt.id].append(section_dict) else: timeslot_dict[mt.id] = [section_dict] for i in range(len(timeslots)): timeslot = timeslots[i] daybreak = False if prevTimeSlot != None: if not Event.contiguous(prevTimeSlot, timeslot): blockCount += 1 daybreak = True if timeslot.id in timeslot_dict: cls_list = timeslot_dict[timeslot.id] doesnt_have_enrollment = not any(sec['section'].is_enrolled for sec in cls_list) schedule.append((timeslot, cls_list, blockCount + 1, doesnt_have_enrollment)) else: schedule.append((timeslot, [], blockCount + 1, False)) prevTimeSlot = timeslot context['num_classes'] = len(classList) context['timeslots'] = schedule context['use_priority'] = scrmi.use_priority context['allow_removal'] = self.deadline_met('/Removal') return context