def __init__(self, *args, **kwargs): super(TeacherInfoForm, self).__init__(*args, **kwargs) if Tag.getTag('teacherinfo_shirt_options') == 'False': del self.fields['shirt_size'] del self.fields['shirt_type'] elif Tag.getTag('teacherinfo_shirt_type_selection') == 'False': del self.fields['shirt_type']
def __init__(self, *args, **kwargs): super(TeacherInfoForm, self).__init__(*args, **kwargs) if Tag.getTag('teacherinfo_shirt_options') == 'False': del self.fields['shirt_size'] del self.fields['shirt_type'] elif Tag.getTag('teacherinfo_shirt_type_selection') == 'False': del self.fields['shirt_type']
def __init__(self, *args, **kwargs): # Extract a program if one was provided if 'program' in kwargs: program = kwargs['program'] del kwargs['program'] else: program = None # Run default init function super(SplashInfoForm, self).__init__(*args, **kwargs) # Set choices from Tag data (try to get program-specific choices if they exist) tag_data = None if program: tag_data = Tag.getTag('splashinfo_choices', target=program) if not tag_data: tag_data = Tag.getTag('splashinfo_choices') if tag_data: tag_struct = json.loads(tag_data) self.fields['lunchsat'].choices = tag_struct['lunchsat'] self.fields['lunchsun'].choices = tag_struct['lunchsun'] if not Tag.getBooleanTag('splashinfo_siblingdiscount', default=True): del self.fields['siblingdiscount'] del self.fields['siblingname'] if not Tag.getBooleanTag('splashinfo_lunchsat', default=True): del self.fields['lunchsat'] if not Tag.getBooleanTag('splashinfo_lunchsun', default=True): del self.fields['lunchsun']
def __init__(self, *args, **kwargs): if 'program' in kwargs: self.program = kwargs['program'] del kwargs['program'] else: raise KeyError( 'Need to supply program as named argument to VolunteerOfferForm' ) super(VolunteerOfferForm, self).__init__(*args, **kwargs) vrs = self.program.getVolunteerRequests() self.fields['requests'].choices = [ (v.id, '%s: %s (%d more needed)' % (v.timeslot.pretty_time(), v.timeslot.description, v.num_volunteers - v.num_offers())) for v in vrs if v.num_offers() < v.num_volunteers ] + [(v.id, '%s: %s (no more needed)' % (v.timeslot.pretty_time(), v.timeslot.description)) for v in vrs if v.num_offers() >= v.num_volunteers] # Show t-shirt fields if specified by Tag (disabled by default) if not Tag.getTag('volunteer_tshirt_options'): del self.fields['shirt_size'] del self.fields['shirt_type'] elif not Tag.getTag('volunteer_tshirt_type_selection'): del self.fields['shirt_type'] if not Tag.getTag('volunteer_allow_comments'): del self.fields['comments']
def __init__(self, *args, **kwargs): super(GuardContactForm, self).__init__(*args, **kwargs) if not Tag.getTag('allow_guardian_no_email'): if Tag.getTag('require_guardian_email'): self.fields['guard_e_mail'].required = True del self.fields['guard_no_e_mail']
def __init__(self, *args, **kwargs): # Extract a program if one was provided if 'program' in kwargs: program = kwargs['program'] del kwargs['program'] else: program = None # Run default init function super(SplashInfoForm, self).__init__(*args, **kwargs) # Set choices from Tag data (try to get program-specific choices if they exist) tag_data = None if program: tag_data = Tag.getTag('splashinfo_choices', target=program) if not tag_data: tag_data = Tag.getTag('splashinfo_choices') if tag_data: tag_struct = json.loads(tag_data) self.fields['lunchsat'].choices = tag_struct['lunchsat'] self.fields['lunchsun'].choices = tag_struct['lunchsun'] if Tag.getTag('splashinfo_siblingdiscount', default='True') == 'False': del self.fields['siblingdiscount'] del self.fields['siblingname'] if Tag.getTag('splashinfo_lunchsat', default='True') == 'False': del self.fields['lunchsat'] if Tag.getTag('splashinfo_lunchsun', default='True') == 'False': del self.fields['lunchsun']
def clean_guard_e_mail(self): if 'guard_e_mail' not in self.cleaned_data or len(self.cleaned_data['guard_e_mail']) < 3: if Tag.getTag('require_guardian_email') and not self.cleaned_data['guard_no_e_mail']: if Tag.getTag('allow_guardian_no_email'): raise forms.ValidationError("Please enter the e-mail address of your parent/guardian. If they do not have access to e-mail, check the appropriate box.") else: raise forms.ValidationError("Please enter the e-mail address of your parent/guardian.") else: return self.cleaned_data['guard_e_mail']
def medliab(self, request, tl, one, two, module, extra, prog): """ Landing page redirecting to med-liab form on Formstack. """ t = Tag.getTag("formstack_id", self.program) v = Tag.getTag("formstack_viewkey", self.program) context = {"formstack_id": t, "formstack_viewkey": v} return render_to_response(self.baseDir() + 'medliab.html', request, context)
def clean_schoolsystem_id(self): if Tag.getTag('schoolsystem'): sysinfo = json.loads(str(Tag.getTag('schoolsystem'))) if 'num_digits' in sysinfo: input_str = self.cleaned_data['schoolsystem_id'].strip() if len(input_str) > 0: if len(input_str) != int(sysinfo['num_digits']) or not input_str.isdigit(): raise forms.ValidationError("Please enter a unique %d-digit number." % int(sysinfo['num_digits'])) if 'check_unique' in sysinfo and sysinfo['check_unique']: if StudentInfo.objects.filter(schoolsystem_id=input_str).exclude(user=self._user).exists(): if len(input_str.strip('0')) != 0: raise forms.ValidationError("Someone else has already entered CPS ID number '%s'." % input_str) return self.cleaned_data['schoolsystem_id']
def phase_2(self): """Testing phase 2, where user provides info, and we make the account""" url = "/myesp/register/" if Tag.getTag("ask_about_duplicate_accounts", default="false").lower() != "false": url += "information/" response = self.client.post(url, data={ "username": "******", "password": "******", "confirm_password": "******", "first_name": "first", "last_name": "last", "email": "*****@*****.**", "confirm_email": "*****@*****.**", "initial_role": "Teacher" }) #test that the user was created properly try: u = ESPUser.objects.get(username="******", first_name="first", last_name="last", email="*****@*****.**") except ESPUser.DoesNotExist, ESPUser.MultipleObjectsReturned: self.fail("User not created correctly or created multiple times")
class Meta: model = FinancialAidRequest tag_data = Tag.getTag('finaid_form_fields') if tag_data: fields = tuple(tag_data.split(',')) else: fields = '__all__'
def get_or_create(cls, label, program=None): if (label, program) in cls._get_or_create_cache: return cls._get_or_create_cache[(label, program)] if program: base_q = Q(program=program) if Tag.getTag('allow_global_restypes'): base_q = base_q | Q(program__isnull=True) else: base_q = Q(program__isnull=True) current_type = ResourceType.objects.filter(base_q).filter(name__icontains=label) if len(current_type) != 0: ret = current_type[0] else: nt = ResourceType() nt.name = label nt.description = '' nt.attributes_pickled = "Yes" nt.program = program nt.autocreated = True nt.save() ret = nt cls._get_or_create_cache[(label, program)] = ret return ret
def clean(self, value): if value is None or value == '': return '' m = _phone_re.match(value) if m: numbers = m.groups() value = "".join(numbers[:3]) + '-' + "".join( numbers[3:6]) + '-' + "".join(numbers[6:]) return value # Check for a Tag containing the default area code. if self.areacode is None: tag_areacode = Tag.getTag('local_areacode') if tag_areacode: self.areacode = tag_areacode if self.areacode is not None: m = _localphone_re.match(value) if m: numbers = m.groups() value = self.areacode + '-' + "".join( numbers[:3]) + '-' + "".join(numbers[3:]) return value raise forms.ValidationError( 'Phone numbers must be a valid US number. "%s" is invalid.' % value)
def phase_1(self): """Testing the phase 1 of registration, the email address page""" #first try an email that shouldn't have an account #first without follow, to see that it redirects correctly response1 = self.client.post("/myesp/register/",data={"email":"*****@*****.**"}) if Tag.getTag('ask_about_duplicate_accounts', default='false').lower() == 'false': self.assertTemplateUsed(response1,"registration/newuser.html") return self.assertRedirects(response1, "/myesp/register/information?email=tsutton125%40gmail.com") #next, make a user with that email and try the same u=ESPUser.objects.create(email="*****@*****.**") response2 = self.client.post("/myesp/register/",data={"email":"*****@*****.**"},follow=True) self.assertTemplateUsed(response2, 'registration/newuser_phase1.html') self.assertContains(response2, "do_reg_no_really") #check when there's a user awaiting activation #(we check with a regex searching for _ in the password, since that #can't happen normally) u.password="******" response3 = self.client.post("/myesp/register/",data={"email":"*****@*****.**"},follow=True) self.assertTemplateUsed(response3, 'registration/newuser_phase1.html') self.assertContains(response3, "do_reg_no_really") #check when you send do_reg_no_really it procedes response4 = self.client.post("/myesp/register/",data={"email":"*****@*****.**","do_reg_no_really":""},follow=False) self.assertRedirects(response4, "/myesp/register/information?email=tsutton125%40gmail.com") response4 = self.client.post("/myesp/register/",data={"email":"*****@*****.**","do_reg_no_really":""},follow=True) self.assertContains(response4, "*****@*****.**")
def user_registration_phase1(request): """Displays phase 1, and receives and passes off phase 1 submissions.""" if request.user.is_authenticated(): return render_to_response('registration/already_logged_in.html', request, request.get_node('Q/Web/myesp'), {}) #depending on a tag, we'll either have registration all in one page, #or in two separate ones if Tag.getTag("ask_about_duplicate_accounts", default="false").lower() == "false": if request.method == 'POST': return user_registration_validate(request) form = SinglePhaseUserRegForm() return render_to_response('registration/newuser.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() }) #we do want to ask about duplicate accounts if request.method == 'POST': return user_registration_checkemail(request) form = EmailUserRegForm() return render_to_response('registration/newuser_phase1.html', request, request.get_node('Q/Web/myesp'), { 'form': form, 'site': Site.objects.get_current() })
def landing(request): context = {} tc = ThemeController() context['theme_name'] = tc.get_current_theme() context['last_customization_name'] = Tag.getTag('prev_theme_customization', default='None') return render_to_response('themes/landing.html', request, context)
def testTagWithTarget(self): '''Test getting and setting of tags with targets.''' # Delete any existing tags that might interfere Tag.objects.filter(key="test").delete() # Dump any existing Tag cache Tag._getTag.delete_all() user, created = User.objects.get_or_create(username="******", email="*****@*****.**", password="") self.assertFalse(Tag.getTag("test", user), "Retrieved a tag for key 'test' target '%s', but we haven't set one yet!" % (user)) Tag.setTag("test", user, "frobbed again") self.assertEqual(Tag.getTag("test", user), "frobbed again") Tag.setTag("test", user) self.assertEqual(Tag.getTag("test", user), Tag.EMPTY_TAG) Tag.unSetTag("test", user) self.assertFalse(Tag.getTag("test", user), "unSetTag() didn't work for per-row tags!")
def copyclasses(self, request, tl, one, two, module, extra, prog): context = {} context['all_class_list'] = request.user.getTaughtClasses() context['noclasses'] = (len(context['all_class_list']) == 0) context['allow_class_import'] = 'false' not in Tag.getTag( 'allow_class_import', default='true').lower() return render_to_response(self.baseDir() + 'listcopyclasses.html', request, context)
def clean(self): super(UserContactForm, self).clean() if self.user.isTeacher() or Tag.getTag('request_student_phonenum', default='True') != 'False': if self.cleaned_data.get('phone_day','') == '' and self.cleaned_data.get('phone_cell','') == '': raise forms.ValidationError("Please provide either a day phone or cell phone number in your personal contact information.") if self.cleaned_data.get('receive_txt_message', None) and self.cleaned_data.get('phone_cell','') == '': raise forms.ValidationError("Please specify your cellphone number if you ask to receive text messages.") return self.cleaned_data
def good_random_class(): constraints = json.loads(Tag.getTag('random_constraints', default='{}')) q = Q() for bad_program_name in constraints.get('bad_program_names', []): q = q & ~Q(parent_program__name__icontains=bad_program_name) for bad_title in constraints.get('bad_titles', []): q = q & ~Q(title__iexact=bad_title) return ClassSubject.objects.random_class(q)
def _checkTeacher(moduleObj, request, *args, **kwargs): allowed_teacher_types = Tag.getTag("allowed_teacher_types", moduleObj.program, default='').split(",") if not_logged_in(request): return HttpResponseRedirect('%s?%s=%s' % (LOGIN_URL, REDIRECT_FIELD_NAME, quote(request.get_full_path()))) if not request.user.isTeacher() and not request.user.isAdmin(moduleObj.program) and not (set(request.user.getUserTypes()) & set(allowed_teacher_types)): return render_to_response('errors/program/notateacher.html', request, (moduleObj.program, 'teach'), {}) return method(moduleObj, request, *args, **kwargs)
def __init__(self, *args, **kwargs): super(TeacherInfoForm, self).__init__(*args, **kwargs) if not Tag.getTag('teacherinfo_reimbursement_options', default=False): reimbursement_fields = ['full_legal_name', 'university_email', 'student_id', 'mail_reimbursement'] for field_name in reimbursement_fields: del self.fields[field_name] if Tag.getTag('teacherinfo_shirt_options') == 'False': del self.fields['shirt_size'] del self.fields['shirt_type'] elif Tag.getTag('teacherinfo_shirt_type_selection') == 'False': del self.fields['shirt_type'] if Tag.getTag('teacherinfo_shirt_size_required'): self.fields['shirt_size'].required = True self.fields['shirt_size'].widget.attrs['class'] = 'required' if Tag.getTag('teacherinfo_reimbursement_checks') == 'False': del self.fields['mail_reimbursement']
def clean(self): super(StudentInfoForm, self).clean() cleaned_data = self.cleaned_data show_studentrep_application = Tag.getTag('show_studentrep_application') if show_studentrep_application and show_studentrep_application != "no_expl": expl = self.cleaned_data['studentrep_expl'].strip() if self.studentrep_error and self.cleaned_data[ 'studentrep'] and expl == '': raise forms.ValidationError( "Please enter an explanation if you would like to become a student rep." ) if not Tag.getTag('allow_change_grade_level'): user = self._user orig_prof = RegistrationProfile.getLastProfile(user) # If graduation year and dob were disabled, get old data. if (orig_prof.id is not None) and (orig_prof.student_info is not None): if not 'graduation_year' in cleaned_data: # Get rid of the error saying this is missing del self.errors['graduation_year'] if not 'dob' in cleaned_data: del self.errors['dob'] # Always use the old birthdate if it exists, so that people can't # use something like Firebug to change their age/grade cleaned_data[ 'graduation_year'] = orig_prof.student_info.graduation_year cleaned_data['dob'] = orig_prof.student_info.dob if Tag.getBooleanTag('require_school_field'): if not cleaned_data['k12school'] and not cleaned_data[ 'unmatched_school']: raise forms.ValidationError( "Please select your school from the dropdown list that appears as you type its name. You will need to click on an entry to select it. If you cannot find your school, please type in its full name and check the box below; we will do our best to add it to our database." ) return cleaned_data
def finaid(self, request, tl, one, two, module, extra, prog): """ Student financial aid requests. This template will redirect the person to an HTTPS address if the appropriate tag is set. """ if Tag.getTag('finaid_directions_step'): return render_to_response(self.baseDir() + 'aid_direct.html', {}) else: return self.finaid_app(request, tl, one, two, module, extra, prog)
def prepare(self, context={}): context['splashinfo'] = SplashInfo.getForUser(get_current_request().user, self.program) if Tag.getTag('splashinfo_siblingdiscount', default='True') == 'False': context['splashinfo'].include_siblingdiscount = False else: context['splashinfo'].include_siblingdiscount = True if Tag.getTag('splashinfo_lunchsat', default='True') == 'False': context['splashinfo'].include_lunchsat = False else: context['splashinfo'].include_lunchsat = True if Tag.getTag('splashinfo_lunchsun', default='True') == 'False': context['splashinfo'].include_lunchsun = False else: context['splashinfo'].include_lunchsun = True return context
def _checkStudent(moduleObj, request, *args, **kwargs): if not_logged_in(request): return HttpResponseRedirect('%s?%s=%s' % (LOGIN_URL, REDIRECT_FIELD_NAME, quote(request.get_full_path()))) if not request.user.isStudent() and not request.user.isAdmin(moduleObj.program): allowed_student_types = Tag.getTag("allowed_student_types", moduleObj.program, default='') matching_user_types = UserBit.valid_objects().filter(user=request.user, verb__parent=GetNode("V/Flags/UserRole"), verb__name__in=allowed_student_types.split(",")) if not matching_user_types: return render_to_response('errors/program/notastudent.html', request, (moduleObj.program, 'learn'), {}) return method(moduleObj, request, *args, **kwargs)
def load_from_tag(cls, theme_name=None, just_selected=False): data = json.loads(Tag.getTag('theme_template_control', default='{}')) if theme_name is None: tc = ThemeController() theme_name = tc.get_current_theme() data['theme'] = theme_name form_temp = cls(initial=data) data = form_temp.recover_from_serialization(data) data['just_selected'] = just_selected form = cls(initial=data) return form
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 load_from_tag(cls, theme_name=None, just_selected=False): data = json.loads(Tag.getTag('theme_template_control', default='{}')) if theme_name is None: tc = ThemeController() theme_name = tc.get_current_theme() data['theme'] = theme_name form_temp = cls(initial=data) data = form_temp.recover_from_serialization(data) data['just_selected'] = just_selected form = cls(initial=data) return form
def get_custom_fields(): result = OrderedDict() form_list_str = Tag.getTag('teacherreg_custom_forms') if form_list_str: form_cls_list = json.loads(form_list_str) for item in form_cls_list: mod = __import__('esp.program.modules.forms.teacherreg_custom', (), (), [item]) cls = getattr(mod, item) for field in cls.base_fields: result[field] = cls.base_fields[field] return result
def get_custom_fields(): result = SortedDict() form_list_str = Tag.getTag('teacherreg_custom_forms') if form_list_str: form_cls_list = json.loads(form_list_str) for item in form_cls_list: mod = __import__('esp.program.modules.forms.teacherreg_custom', (), (), [item]) cls = getattr(mod, item) for field in cls.base_fields: result[field] = cls.base_fields[field] return result
def render_qsd(qsd): # check whether we should display the date and author footer (only affects non-administrator users) display_date_author_tag = Tag.getTag('qsd_display_date_author', default='Both') display_date_author = 2 # display date and author if display_date_author_tag == 'Date': display_date_author = 1 # display date only elif display_date_author_tag == 'None': display_date_author = 0 # hide footer return {'qsdrec': qsd, 'display_date_author' : display_date_author}
def filter_username(username, password): # Allow login by e-mail address if so specified if username and '@' in username and Tag.getTag('login_by_email'): accounts = ESPUser.objects.filter(email=username) matches = [] for u in accounts: if u.check_password(password): matches.append(u) if len(matches) > 0: username = matches[0].username return username
def render_qsd(qsd): # check whether we should display the date and author footer (only affects non-administrator users) display_date_author_tag = Tag.getTag('qsd_display_date_author', default='Both') display_date_author = 2 # display date and author if display_date_author_tag == 'Date': display_date_author = 1 # display date only elif display_date_author_tag == 'None': display_date_author = 0 # hide footer return {'qsdrec': qsd, 'display_date_author': display_date_author}
def __init__(self, *args, **kwargs): if 'program' in kwargs: self.program = kwargs['program'] del kwargs['program'] else: raise KeyError('Need to supply program as named argument to VolunteerOfferForm') super(VolunteerOfferForm, self).__init__(*args, **kwargs) vrs = self.program.getVolunteerRequests() self.fields['requests'].choices = [(v.id, '%s: %s (%d more needed)' % (v.timeslot.pretty_time(), v.timeslot.description, v.num_volunteers - v.num_offers())) for v in vrs if v.num_offers() < v.num_volunteers] + [(v.id, '%s: %s (no more needed)' % (v.timeslot.pretty_time(), v.timeslot.description)) for v in vrs if v.num_offers() >= v.num_volunteers] # Show t-shirt fields if specified by Tag (disabled by default) if not Tag.getTag('volunteer_tshirt_options'): del self.fields['shirt_size'] del self.fields['shirt_type'] elif not Tag.getTag('volunteer_tshirt_type_selection'): del self.fields['shirt_type'] if not Tag.getTag('volunteer_allow_comments'): del self.fields['comments']
def testTagWithTarget(self): '''Test getting and setting of tags with targets.''' # Delete any existing tags that might interfere Tag.objects.filter(key="test").delete() # Dump any existing Tag cache Tag._getTag.delete_all() user, created = User.objects.get_or_create(username="******", email="*****@*****.**", password="") self.assertFalse( Tag.getTag("test", user), "Retrieved a tag for key 'test' target '%s', but we haven't set one yet!" % (user)) Tag.setTag("test", user, "frobbed again") self.assertEqual(Tag.getTag("test", user), "frobbed again") Tag.setTag("test", user) self.assertEqual(Tag.getTag("test", user), Tag.EMPTY_TAG) Tag.unSetTag("test", user) self.assertFalse(Tag.getTag("test", user), "unSetTag() didn't work for per-row tags!")
def get_palette(self): palette_base = json.loads(Tag.getTag('current_theme_palette', default='[]')) # Augment with the colors from any global LESS variables palette = set(palette_base) base_vars = self.find_less_variables() for varset in base_vars.values(): for val in varset.values(): if isinstance(val, basestring) and val.startswith('#'): palette.add(val) palette = list(palette) palette.sort() return palette
def clean(self): super(StudentInfoForm, self).clean() cleaned_data = self.cleaned_data show_studentrep_application = Tag.getTag('show_studentrep_application') if show_studentrep_application and show_studentrep_application != "no_expl": expl = self.cleaned_data['studentrep_expl'].strip() if self.studentrep_error and self.cleaned_data['studentrep'] and expl == '': raise forms.ValidationError("Please enter an explanation if you would like to become a student rep.") if not Tag.getTag('allow_change_grade_level'): user = self._user orig_prof = RegistrationProfile.getLastProfile(user) # If graduation year and dob were disabled, get old data. if (orig_prof.id is not None) and (orig_prof.student_info is not None): if not 'graduation_year' in cleaned_data: # Get rid of the error saying this is missing del self.errors['graduation_year'] if not 'dob' in cleaned_data: del self.errors['dob'] # Always use the old birthdate if it exists, so that people can't # use something like Firebug to change their age/grade cleaned_data['graduation_year'] = orig_prof.student_info.graduation_year cleaned_data['dob'] = orig_prof.student_info.dob if Tag.getBooleanTag('require_school_field'): if not cleaned_data['k12school'] and not cleaned_data['unmatched_school']: raise forms.ValidationError("Please select your school from the dropdown list that appears as you type its name. You will need to click on an entry to select it. If you cannot find your school, please type in its full name and check the box below; we will do our best to add it to our database.") return cleaned_data
def __init__(self, *args, **kwargs): # Get tag data in the form of a dictionary: # field name -> tag to look up for initial value if 'tag_map' in kwargs: tag_map = kwargs['tag_map'] tag_defaults = {} for field_name in tag_map: # Check for existence of tag tag_data = Tag.getTag(tag_map[field_name]) # Use tag data as initial value if the tag was found if tag_data: tag_defaults[field_name] = tag_data if 'initial' not in kwargs: kwargs['initial'] = {} # Apply defaults to form quietly (don't override provided values) for key in tag_defaults: if key not in kwargs['initial']: kwargs['initial'][key] = tag_defaults[key] # Remove the tag_map so as not to confuse other functions del kwargs['tag_map'] super(FormWithTagInitialValues, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): super(TeacherProfileForm, self).__init__(*args, **kwargs) for field_name in Tag.getTag('teacher_profile_hide_fields', default='').split(','): if field_name in self.fields: del self.fields[field_name]
def testTagCaching(self): '''Test that tag values are being cached.''' # Delete any existing tags that might interfere Tag.objects.filter(key="test").delete() # Dump any existing Tag cache Tag._getTag.delete_all() user1, created = User.objects.get_or_create(username="******", email="*****@*****.**", password="") user2, created = User.objects.get_or_create(username="******", email="*****@*****.**", password="") for target in [None,user1,user2]: self.assertFalse(Tag.getTag("test",target=target)) with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=target)) self.assertFalse(Tag.getTag("test",target=target)) Tag.setTag("test",value="tag value") for target in [user1,user2]: self.assertFalse(Tag.getTag("test",target=target)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=target)) self.assertFalse(Tag.getTag("test",target=target)) self.assertEqual(Tag.getTag("test"),"tag value") with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test"),"tag value") self.assertEqual(Tag.getTag("test"),"tag value") for target in [user1,user2]: self.assertFalse(Tag.getTag("test",target=target)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=target)) self.assertFalse(Tag.getTag("test",target=target)) Tag.setTag("test",value="tag value 2") for target in [user1,user2]: self.assertFalse(Tag.getTag("test",target=target)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=target)) self.assertFalse(Tag.getTag("test",target=target)) self.assertEqual(Tag.getTag("test"),"tag value 2") with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test"),"tag value 2") self.assertEqual(Tag.getTag("test"),"tag value 2") for target in [user1,user2]: self.assertFalse(Tag.getTag("test",target=target)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=target)) self.assertFalse(Tag.getTag("test",target=target)) Tag.setTag("test",target=user1,value="tag value user1") self.assertFalse(Tag.getTag("test",target=user2)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=user2)) self.assertFalse(Tag.getTag("test",target=user2)) self.assertEqual(Tag.getTag("test"),"tag value 2") #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test"),"tag value 2") self.assertEqual(Tag.getTag("test"),"tag value 2") self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") self.assertEqual(Tag.getTag("test"),"tag value 2") #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test"),"tag value 2") self.assertEqual(Tag.getTag("test"),"tag value 2") self.assertFalse(Tag.getTag("test",target=user2)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=user2)) self.assertFalse(Tag.getTag("test",target=user2)) Tag.unSetTag("test") self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") self.assertFalse(Tag.getTag("test",target=user2)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=user2)) self.assertFalse(Tag.getTag("test",target=user2)) self.assertFalse(Tag.getTag("test")) with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test")) self.assertFalse(Tag.getTag("test")) self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") self.assertEqual(Tag.getTag("test",target=user1),"tag value user1") self.assertFalse(Tag.getTag("test",target=user2)) #remove after Issue #866 is fixed with self.assertNumQueries(0): self.assertFalse(Tag.getTag("test",target=user2)) self.assertFalse(Tag.getTag("test",target=user2))
def __init__(self, crmi, *args, **kwargs): from esp.program.controllers.classreg import get_custom_fields def hide_field(field, default=None): field.widget = forms.HiddenInput() if default is not None: field.initial = default def hide_choice_if_useless(field): """ Hide a choice field if there's only one choice """ if len(field.choices) == 1: hide_field(field, default=field.choices[0][0]) super(TeacherClassRegForm, self).__init__(*args, **kwargs) prog = crmi.program section_numbers = crmi.allowed_sections_actual section_numbers = zip(section_numbers, section_numbers) class_sizes = crmi.getClassSizes() class_sizes = zip(class_sizes, class_sizes) class_grades = crmi.getClassGrades() class_grades = zip(class_grades, class_grades) class_ranges = ClassSizeRange.get_ranges_for_program(prog) class_ranges = [(range.id, range.range_str()) for range in class_ranges] # num_sections: section_list; hide if useless self.fields['num_sections'].choices = section_numbers hide_choice_if_useless( self.fields['num_sections'] ) # category: program.class_categories.all() self.fields['category'].choices = [ (x.id, x.category) for x in prog.class_categories.all() ] # grade_min, grade_max: crmi.getClassGrades self.fields['grade_min'].choices = class_grades self.fields['grade_max'].choices = class_grades if crmi.use_class_size_max: # class_size_max: crmi.getClassSizes self.fields['class_size_max'].choices = class_sizes else: del self.fields['class_size_max'] if Tag.getBooleanTag('use_class_size_optimal', default=False): if not crmi.use_class_size_optimal: del self.fields['class_size_optimal'] if crmi.use_optimal_class_size_range: self.fields['optimal_class_size_range'].choices = class_ranges else: del self.fields['optimal_class_size_range'] if crmi.use_allowable_class_size_ranges: self.fields['allowable_class_size_ranges'].choices = class_ranges else: del self.fields['allowable_class_size_ranges'] else: del self.fields['class_size_optimal'] del self.fields['optimal_class_size_range'] del self.fields['allowable_class_size_ranges'] # decide whether to display certain fields # prereqs if not crmi.set_prereqs: self.fields['prereqs'].widget = forms.HiddenInput() # allow_lateness if not crmi.allow_lateness: self.fields['allow_lateness'].widget = forms.HiddenInput() self.fields['allow_lateness'].initial = 'False' self.fields['duration'].choices = sorted(crmi.getDurations()) hide_choice_if_useless( self.fields['duration'] ) # session_count if crmi.session_counts: session_count_choices = crmi.session_counts_ints session_count_choices = zip(session_count_choices, session_count_choices) self.fields['session_count'].choices = session_count_choices hide_choice_if_useless( self.fields['session_count'] ) # requested_room if not crmi.ask_for_room: hide_field( self.fields['requested_room'] ) # Hide resource fields since separate forms are now being used. - Michael P # Most have now been removed, but this one gets un-hidden by open classes. self.fields['requested_special_resources'].widget = forms.HiddenInput() # Add program-custom form components (for inlining additional questions without # introducing a separate program module) custom_fields = get_custom_fields() for field_name in custom_fields: self.fields[field_name] = custom_fields[field_name] # Modify help text on these fields if necessary. custom_helptext_fields = ['duration', 'class_size_max', 'num_sections', 'requested_room', 'message_for_directors', 'purchase_requests', 'class_info'] + custom_fields.keys() for field in custom_helptext_fields: tag_data = Tag.getProgramTag('teacherreg_label_%s' % field, prog) if tag_data: self.fields[field].label = tag_data tag_data = Tag.getProgramTag('teacherreg_help_text_%s' % field, prog) if tag_data: self.fields[field].help_text = tag_data # Hide fields as desired. tag_data = Tag.getProgramTag('teacherreg_hide_fields', prog) if tag_data: for field_name in tag_data.split(','): hide_field(self.fields[field_name]) tag_data = Tag.getProgramTag('teacherreg_default_min_grade', prog) if tag_data: self.fields['grade_min'].initial = tag_data tag_data = Tag.getProgramTag('teacherreg_default_max_grade', prog) if tag_data: self.fields['grade_max'].initial = tag_data tag_data = Tag.getProgramTag('teacherreg_default_class_size_max', prog) if tag_data: self.fields['class_size_max'].initial = tag_data # Rewrite difficulty label/choices if desired: if Tag.getTag('teacherreg_difficulty_choices'): self.fields['hardness_rating'].choices = json.loads(Tag.getTag('teacherreg_difficulty_choices'))
def charge_payment(self, request, tl, one, two, module, extra, prog): # Check for setup of module. This is also required to initialize settings. self.check_setup() context = {'postdata': request.POST.copy()} group_name = Tag.getTag('full_group_name') or '%s %s' % (settings.INSTITUTION_NAME, settings.ORGANIZATION_SHORT_NAME) iac = IndividualAccountingController(self.program, request.user) # Set Stripe key based on settings. Also require the API version # which our code is designed for. stripe.api_key = self.settings['secret_key'] # We are using the 2014-03-13 version of the Stripe API, which is # v1.12.2. stripe.api_version = '2014-03-13' if request.POST.get('ponumber', '') != iac.get_id(): # If we received a payment for the wrong PO: # This is not a Python exception, but an error nonetheless. context['error_type'] = 'inconsistent_po' context['error_info'] = {'request_po': request.POST.get('ponumber', ''), 'user_po': iac.get_id()} if 'error_type' not in context: # Check the amount in the POST against the amount in our records. # If they don't match, raise an error. amount_cents_post = Decimal(request.POST['totalcost_cents']) amount_cents_iac = Decimal(iac.amount_due()) * 100 if amount_cents_post != amount_cents_iac: context['error_type'] = 'inconsistent_amount' context['error_info'] = { 'amount_cents_post': amount_cents_post, 'amount_cents_iac': amount_cents_iac, } if 'error_type' not in context: try: with transaction.atomic(): # Save a record of the charge if we can uniquely identify the user/program. # If this causes an error, the user will get a 500 error # page, and the card will NOT be charged. # If an exception is later raised by # stripe.Charge.create(), then the transaction will be # rolled back. # Thus, we will never be in a state where the card has been # charged without a record being created on the site, nor # vice-versa. totalcost_dollars = Decimal(request.POST['totalcost_cents']) / 100 # Create a record of the transfer without the transaction ID. transfer = iac.submit_payment(totalcost_dollars, 'TBD') # Create the charge on Stripe's servers - this will charge # the user's card. charge = stripe.Charge.create( amount=amount_cents_post, currency="usd", card=request.POST['stripeToken'], description="Payment for %s %s - %s" % (group_name, prog.niceName(), request.user.name()), statement_descriptor=group_name[0:22], #stripe limits statement descriptors to 22 characters metadata={ 'ponumber': request.POST['ponumber'], }, ) # Now that the charge has been performed by Stripe, save its # transaction ID for our records. transfer.transaction_id = charge.id transfer.save() except stripe.error.CardError, e: context['error_type'] = 'declined' context['error_info'] = e.json_body['error'] except stripe.error.InvalidRequestError, e: # While this is a generic error meaning invalid parameters were supplied # to Stripe's API, we will usually see it because of a duplicate request. context['error_type'] = 'invalid'
def __init__(self, user=None, *args, **kwargs): from esp.users.models import ESPUser super(StudentInfoForm, self).__init__(user, *args, **kwargs) self.allow_change_grade_level = Tag.getTag('allow_change_grade_level') ## All of these Tags may someday want to be made per-program somehow. ## We don't know the current program right now, though... show_studentrep_application = Tag.getTag('show_studentrep_application') if not show_studentrep_application: ## Only enable the Student Rep form optionally. del self.fields['studentrep'] if (not show_studentrep_application) or show_studentrep_application == "no_expl": del self.fields['studentrep_expl'] if not Tag.getTag('show_student_tshirt_size_options'): del self.fields['shirt_size'] del self.fields['shirt_type'] elif Tag.getTag('studentinfo_shirt_type_selection') == 'False': del self.fields['shirt_type'] if not Tag.getTag('show_student_vegetarianism_options'): del self.fields['food_preference'] # Allow grade range of students to be customized by a Tag (default is 7-12) self.fields['graduation_year'].choices = [('','')]+[(str(ESPUser.YOGFromGrade(x)), str(x)) for x in ESPUser.grade_options()] # Add user's current grade if it is out of range and they have already filled out the profile. if user and user.registrationprofile_set.count() > 0: user_grade = user.getGrade() grade_tup = (str(ESPUser.YOGFromGrade(user_grade)), str(user_grade)) if grade_tup not in self.fields['graduation_year'].choices: self.fields['graduation_year'].choices.insert(0, grade_tup) # Honor several possible Tags for customizing the fields that are displayed. if Tag.getTag('show_student_graduation_years_not_grades'): current_grad_year = self.ESPUser.current_schoolyear() new_choices = [] for x in self.fields['graduation_year'].choices: if len(x[0]) > 0: new_choices.append((str(x[0]), "%s (%sth grade)" % (x[0], x[1]))) else: new_choices.append(x) self.fields['graduation_year'].choices = new_choices if not Tag.getBooleanTag('student_profile_gender_field'): del self.fields['gender'] if not Tag.getTag('ask_student_about_transportation_to_program'): del self.fields['transportation'] if not Tag.getTag('allow_change_grade_level'): if 'initial' in kwargs: initial_data = kwargs['initial'] # Disable the age and grade fields if they already exist. if 'graduation_year' in initial_data and 'dob' in initial_data: self.fields['graduation_year'].widget.attrs['disabled'] = "true" self.fields['graduation_year'].required = False self.fields['dob'].widget.attrs['disabled'] = "true" self.fields['dob'].required = False # Add field asking about medical needs if directed by the Tag if Tag.getTag('student_medical_needs'): self.fields['medical_needs'].widget = forms.Textarea(attrs={'cols': 40, 'rows': 3}) else: del self.fields['medical_needs'] # The unmatched_school field is for students to opt out of selecting a K12School. # If we don't require a K12School to be selected, don't bother showing that field. if not Tag.getBooleanTag('require_school_field', default=False): del self.fields['unmatched_school'] self._user = user
def classList_base(self, request, tl, one, two, module, extra, prog, options=None, template_name='classlist.html'): """ Display a list of all classes that still have space in them """ # Allow options to be supplied as an argument to the view function, in lieu # of request.GET (used by the public view just above) if options is None: options = request.GET.copy() # Display options-selection page if this page is requested with no GET variables if len(options.keys()) == 0: return render_to_response(self.baseDir() + 'classlist_options.html', request, {'prog': prog}) context = {} defaults = {'refresh': 120, 'scrollspeed': 1} for key_option in defaults.keys(): if key_option in options: context[key_option] = options[key_option] else: context[key_option] = defaults[key_option] time_now = datetime.now() start_id = int(options.get('start', -1)) if start_id != -1: curtime = Event.objects.filter(id=start_id) else: window_start = time_now + timedelta(-1, 85200) # 20 minutes ago curtime = Event.objects.filter(start__gte=window_start, event_type__description='Class Time Block').order_by('start') end_id = int(options.get('end', -1)) if end_id != -1: endtime = Event.objects.filter(id=end_id) else: endtime = None sort_spec = options.get('sorting', None) if sort_spec is None: sort_spec = extra # Enforce a maximum refresh speed to avoid server overload. min_refresh = int(Tag.getTag('onsite_classlist_min_refresh', default='10')) if int(context['refresh']) < min_refresh: context['refresh'] = min_refresh if curtime: curtime = curtime[0] if endtime: endtime = endtime[0] classes = self.program.sections().annotate(begin_time=Min("meeting_times__start")).filter( status=10, parent_class__status=10, begin_time__gte=curtime.start, begin_time__lte=endtime.start ) else: classes = self.program.sections().annotate(begin_time=Min("meeting_times__start")).filter( status=10, parent_class__status=10, begin_time__gte=curtime.start ) if sort_spec == 'unsorted': classes = classes.order_by('begin_time', 'id').distinct() elif sort_spec == 'by_time': classes = classes.order_by('begin_time', 'parent_class__category', 'id').distinct() else: classes = classes.order_by('parent_class__category', 'begin_time', 'id').distinct() context.update({'prog': prog, 'current_time': curtime, 'classes': classes, 'one': one, 'two': two}) if sort_spec == 'unsorted': context['use_categories'] = False else: context['use_categories'] = True return render_to_response(self.baseDir()+template_name, request, context)
def testTagGetSet(self): """ Test that the get and set methods for tags, work. Note that at this time, I assume that GenericForeignKeys work and are invoked correctly on this class. """ # Dump any existing Tag cache Tag._getTag.delete_all() self.assertFalse(bool(Tag.getTag("test")), "Retrieved a tag for key 'test' but we haven't set one yet!") self.assertFalse(Tag.getTag("test"), "getTag() created a retrievable value for key 'test'!") self.assertEqual(Tag.getTag("test",default="the default"),"the default") self.assertEqual(Tag.getTag("test",default="the default"),"the default") Tag.setTag("test", value="frobbed") self.assertEqual(Tag.getTag("test"), "frobbed", "Failed to set tag 'test' to value 'frobbed'!") self.assertEqual(Tag.getTag("test"), "frobbed", "Tag was created, but didn't stick!") self.assertEqual(Tag.getTag("test",default="the default"), "frobbed", "Defaulting is borked!") self.assertEqual(Tag.getTag("test",default="the default"), "frobbed", "Defaulting is borked!") Tag.unSetTag("test") self.assertFalse(Tag.getTag("test"), "Retrieved a tag for key 'test' but we just deleted it!") self.assertFalse(Tag.getTag("test"), "unSetTag() deletes don't appear to be persistent!") self.assertEqual(Tag.getTag("test",default="the default"),"the default") self.assertEqual(Tag.getTag("test",default="the default"),"the default") Tag.setTag("test") self.assertTrue(Tag.getTag("test"), "Error: Setting a tag with an unspecified value must yield a tag whose value evaluates to True!") self.assertNotEqual(Tag.getTag("test",default="the default"),"the default","If the tag is set, even to EMPTY_TAG, we shouldn't return the default.")