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.getProgramTag('splashinfo_choices', 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 user_registration_validate(request): """Handle the account creation logic when the form is submitted This function is overloaded to handle either one or two phase reg""" if not Tag.getBooleanTag("ask_about_duplicate_accounts", default=False): form = SinglePhaseUserRegForm(request.POST) else: form = UserRegForm(request.POST) if form.is_valid(): try: #there is an email-only account with that email address to upgrade user = ESPUser.objects.get(email=form.cleaned_data['email'], password='******') except ESPUser.DoesNotExist: try: #there is an inactive account with that username user = ESPUser.objects.filter( username=form.cleaned_data['username'], is_active=False).latest('date_joined') except ESPUser.DoesNotExist: user = ESPUser.objects.create_user( username=form.cleaned_data['username'], email=form.cleaned_data['email']) user.username = form.cleaned_data['username'] user.last_name = form.cleaned_data['last_name'] user.first_name = form.cleaned_data['first_name'] user.set_password(form.cleaned_data['password']) # Append key to password and disable until activation if desired if Tag.getBooleanTag('require_email_validation', default=False): userkey = random.randint(0, 2**31 - 1) user.password += "_%d" % userkey user.is_active = False user.save() user.groups.add( Group.objects.get(name=form.cleaned_data['initial_role'])) if not Tag.getBooleanTag('require_email_validation', default=False): user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) login(request, user) return HttpResponseRedirect('/myesp/profile/') else: send_activation_email(user, userkey) return render_to_response( 'registration/account_created_activation_required.html', request, { 'user': user, 'site': Site.objects.get_current() }) else: return render_to_response('registration/newuser.html', request, {'form': form})
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 phasezero(self, request, tl, one, two, module, extra, prog): context = {} role = str(prog) + " Winners" context['role'] = role q_phasezero = Q(phasezerorecord__program=self.program) entrants = ESPUser.objects.filter(q_phasezero).distinct() context['entrants'] = entrants context['nentrants'] = len(entrants) grades = range(prog.grade_min, prog.grade_max + 1) stats = {} #Calculate grade counts for grade in grades: stats[grade] = {} stats[grade]['in_lottery'] = 0 for entrant in entrants: stats[entrant.getGrade(prog)]['in_lottery'] += 1 #Run lottery if requested if request.POST: if Tag.getBooleanTag('student_lottery_run', prog, default=False): context['error'] = "You've already run the student lottery!" else: if "confirm" in request.POST: if Tag.getProgramTag('program_size_by_grade', prog): role = request.POST['rolename'] context['role'] = role self.lottery(prog, role) context[ 'success'] = "The student lottery has been run successfully." else: context[ 'error'] = "You haven't set the grade caps tag yet." else: context[ 'error'] = "You did not confirm that you would like to run the lottery" #If lottery has been run, calculate acceptance stats if Tag.getBooleanTag('student_lottery_run', prog, default=False): for grade in grades: stats[grade]['num_accepted'] = stats[grade]['per_accepted'] = 0 winners = ESPUser.objects.filter(groups__name=role).distinct() for winner in winners: stats[winner.getGrade(prog)]['num_accepted'] += 1 for grade in grades: if stats[grade]['in_lottery'] == 0: stats[grade]['per_accepted'] = "NA" else: stats[grade]['per_accepted'] = round( stats[grade]['num_accepted'], 1) / stats[grade]['in_lottery'] * 100 context['stats'] = stats return render_to_response( 'program/modules/studentregphasezero/status.html', request, context)
def __init__(self, *args, **kwargs): super(UserContactForm, self).__init__(*args, **kwargs) if not Tag.getBooleanTag('request_student_phonenum', default=True): del self.fields['phone_day'] if not Tag.getBooleanTag('text_messages_to_students') or not self.user.isStudent(): del self.fields['receive_txt_message'] if not self.user.isTeacher() or Tag.getBooleanTag('teacher_address_required', default = True): self.fields['address_street'].required = True self.fields['address_city'].required = True self.fields['address_state'].required = True self.fields['address_zip'].required = 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 phase_2(self): """Testing phase 2, where user provides info, and we make the account""" url = "/myesp/register/" if Tag.getBooleanTag("ask_about_duplicate_accounts", default=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")
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":"*****@*****.**", "confirm_email":"*****@*****.**"}) if not Tag.getBooleanTag('ask_about_duplicate_accounts', default=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":"*****@*****.**", "confirm_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":"*****@*****.**", "confirm_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":"*****@*****.**", "confirm_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":"*****@*****.**", "confirm_email":"*****@*****.**","do_reg_no_really":""},follow=True) self.assertContains(response4, "*****@*****.**")
def user_registration_checkemail(request): """Method to handle the first phase of registration when submitted as a form. The method user_registration_phase1 calls this function when it's given a POST request. When the form isn't valid, re-render the same template but with the form errors. When there are already accounts with this email address (depending on some tags), give the user information about them before proceeding. """ form = EmailUserRegForm(request.POST) if form.is_valid(): ## First, check to see if we have any users with the same e-mail if not 'do_reg_no_really' in request.POST and Tag.getBooleanTag('ask_about_duplicate_accounts', default=False): existing_accounts = ESPUser.objects.filter(email=form.cleaned_data['email'], is_active=True).exclude(password='******') awaiting_activation_accounts = ESPUser.objects.filter(email=form.cleaned_data['email']).filter(is_active=False, password__regex='\$(.*)_').exclude(password='******') if len(existing_accounts)+len(awaiting_activation_accounts) != 0: #they have accounts. go back to the same page, but ask them #if they want to try to log in return render_to_response( 'registration/newuser_phase1.html', request, { 'accounts': existing_accounts,'awaitings':awaiting_activation_accounts, 'email':form.cleaned_data['email'], 'site': Site.objects.get_current(), 'form': form }) #form is valid, and not caring about multiple accounts email = urllib.quote(form.cleaned_data['email']) return HttpResponseRedirect(reverse('users.views.user_registration_phase2')+'?email='+email) else: #form is not valid return render_to_response('registration/newuser_phase1.html', request, {'form':form, 'site': Site.objects.get_current()})
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, {}) #depending on a tag, we'll either have registration all in one page, #or in two separate ones if not Tag.getBooleanTag("ask_about_duplicate_accounts",default=False): if request.method == 'POST': return user_registration_validate(request) form=SinglePhaseUserRegForm() return render_to_response('registration/newuser.html', request, {'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, {'form':form, 'site': Site.objects.get_current()})
def registration_redirect(request): """ A view which returns: - A redirect to the currently open registration if exactly one registration is open - A list of open registration links otherwise """ from esp.users.models import ESPUser from esp.program.models import Program # Make sure we have an ESPUser user = ESPUser(request.user) # prepare the rendered page so it points them to open student/teacher reg's ctxt = {} userrole = {} regperm = None if user.isStudent(): userrole['name'] = 'Student' userrole['base'] = 'learn' userrole['reg'] = 'studentreg' regperm = 'Student/Classes' elif user.isTeacher(): userrole['name'] = 'Teacher' userrole['base'] = 'teach' userrole['reg'] = 'teacherreg' regperm = 'Teacher/Classes' else: # Default to student registration (this will only show if the program # is found via the 'allowed_student_types' Tag) userrole['name'] = user.getUserTypes()[0] userrole['base'] = 'learn' userrole['reg'] = 'studentreg' ctxt['userrole'] = userrole if regperm: progs_deadline = list(Permission.program_by_perm(user, regperm)) else: progs_deadline = [] progs_tag = list(t.target \ for t in Tag.objects.filter(key = "allowed_student_types").select_related() \ if isinstance(t.target, Program) \ and (set(user.getUserTypes()) & set(t.value.split(",")))) progs = list(set(progs_deadline + progs_tag)) #distinct ones # If we have 1 program, automatically redirect to registration for that program. # Most chapters will want this, but it can be disabled by a Tag. if len(progs) == 1 and Tag.getBooleanTag('automatic_registration_redirect', default=True): ctxt['prog'] = progs[0] return HttpResponseRedirect( u'/%s/%s/%s' % (userrole['base'], progs[0].getUrlBase(), userrole['reg'])) else: if len(progs) > 0: # Sort available programs newest first progs.sort(key=lambda x: -x.id) ctxt['progs'] = progs ctxt['prog'] = progs[0] return render_to_response('users/profile_complete.html', request, ctxt)
def clean(self): super(UserContactForm, self).clean() if self.user.isTeacher() or Tag.getBooleanTag('request_student_phonenum', default=True): 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 render_class_teacher_list_row(cls): """Render a class for the teacher list of classes in teacherreg.""" return {'cls': cls, 'program': cls.parent_program, 'crmi': cls.parent_program.classregmoduleinfo, 'friendly_times_with_date': Tag.getBooleanTag( 'friendly_times_with_date', cls.parent_program, False), 'email_host_sender': settings.EMAIL_HOST_SENDER }
def catalog_render(self, request, tl, one, two, module, extra, prog, timeslot=None): """ Return the program class catalog """ # using .extra() to select all the category text simultaneously classes = ClassSubject.objects.catalog(self.program) categories = {} for cls in classes: categories[cls.category_id] = {'id':cls.category_id, 'category':cls.category_txt if hasattr(cls, 'category_txt') else cls.category.category} # Allow tag configuration of whether class descriptions get collapsed # when the class is full (default: yes) collapse_full = Tag.getBooleanTag('collapse_full_classes', prog, True) context = {'classes': classes, 'one': one, 'two': two, 'categories': categories.values(), 'collapse_full': collapse_full} scrmi = prog.studentclassregmoduleinfo context['register_from_catalog'] = scrmi.register_from_catalog prog_color = prog.getColor() collapse_full_classes = Tag.getBooleanTag('collapse_full_classes', prog, True) class_blobs = [] category_header_str = """<hr size="1"/> <a name="cat%d"></a> <p style="font-size: 1.2em;" class="category"> %s </p> <p class="linktop"> <a href="#top">[ Return to Category List ]</a> </p> """ class_category_id = None for cls in classes: if cls.category.id != class_category_id: class_category_id = cls.category.id class_blobs.append(category_header_str % (class_category_id, cls.category.category)) class_blobs.append(render_class_direct(cls)) class_blobs.append('<br />') context['class_descs'] = ''.join(class_blobs) # Include the program explicitly; this is a cached page, without RequestContext context['program'] = self.program return render_to_response(self.baseDir()+'catalog.html', request, context, use_request_context=False)
def render_class_helper(cls, user=None, prereg_url=None, filter=False, timeslot=None): errormsg = None if timeslot: section = cls.get_section(timeslot=timeslot) else: section = None # Add ajax_addclass to prereg_url if registering from catalog is allowed ajax_prereg_url = None scrmi = cls.parent_program.getModuleExtension('StudentClassRegModuleInfo') crmi = cls.parent_program.getModuleExtension('ClassRegModuleInfo') # Ensure cached catalog shows buttons and fillslots don't # NOTE: I believe that this is deprecated; it isn't referred to anywhere. # Which means that scrmi.register_from_catalog is currently useless. # This should be fixed. -jmoldow 11/06/2011 if scrmi.register_from_catalog and not timeslot: ajax_prereg_url = cls.parent_program.get_learn_url() + 'ajax_addclass' prereg_url = None if not (crmi.open_class_registration and cls.category == cls.parent_program.open_class_category): prereg_url = cls.parent_program.get_learn_url() + 'addclass' if user and prereg_url and timeslot: errormsg = cls.cannotAdd(user, which_section=section) show_class = (not filter) or (not errormsg) return { 'class': cls, 'section': section, 'user': user, 'prereg_url': prereg_url, 'ajax_prereg_url': ajax_prereg_url, 'errormsg': errormsg, 'temp_full_message': scrmi.temporarily_full_text, 'show_class': show_class, 'hide_full': Tag.getBooleanTag('hide_full_classes', cls.parent_program, False) }
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 render(self, context): key = self.key.resolve(context) if self.program: program = self.program.resolve(context) else: program = None if self.default: default = self.default.resolve(context) else: default = None if self.boolean: return str(Tag.getBooleanTag(key, program, default)).lower() else: return str(Tag.getProgramTag(key, program, default))
def render_class_teacher_list_row(cls): """Render a class for the teacher list of classes in teacherreg.""" return { 'cls': cls, 'program': cls.parent_program, 'crmi': cls.parent_program.classregmoduleinfo, 'friendly_times_with_date': Tag.getBooleanTag('friendly_times_with_date', cls.parent_program, False), 'email_host_sender': settings.EMAIL_HOST_SENDER }
def user_registration_phase2(request): """Displays the second part of account creation, and when that form is submitted, call a function to handle the actual validation and creation.""" if request.method == 'POST': return user_registration_validate(request) if not Tag.getBooleanTag("ask_about_duplicate_accounts",default=False): return HttpResponseRedirect(reverse("users.views.user_registration_phase1")) try: email = urllib.unquote(request.GET['email']) except MultiValueDictKeyError: return HttpResponseRedirect(reverse("users.views.user_registration_phase1")) form = UserRegForm(initial={'email':email,'confirm_email':email}) return render_to_response('registration/newuser.html', request, {'form':form, 'email':email})
def render_class_core(cls): """Render non-user-specific parts of a class for the catalog.""" prog = cls.parent_program scrmi = prog.studentclassregmoduleinfo colorstring = prog.getColor() if colorstring is not None: colorstring = ' background-color:#' + colorstring + ';' # Allow tag configuration of whether class descriptions get collapsed # when the class is full (default: yes) collapse_full = Tag.getBooleanTag('collapse_full_classes', prog, True) return {'class': cls, 'collapse_full': collapse_full, 'colorstring': colorstring, 'show_enrollment': scrmi.visible_enrollments, 'show_emailcodes': scrmi.show_emailcodes, 'show_meeting_times': scrmi.visible_meeting_times}
def render(self, context): key = self.key.resolve(context) if self.program: program = self.program.resolve(context) else: program = None if self.default: default = self.default.resolve(context) else: default = None if self.boolean: result = Tag.getBooleanTag(key, program, default) if isinstance(result, bool): return str(result).lower() else: return 'false' else: return str(Tag.getProgramTag(key, program, default))
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 registration_redirect(request): """ A view which returns: - A redirect to the currently open registration if exactly one registration is open - A list of open registration links otherwise """ from esp.users.models import ESPUser from esp.program.models import Program user = request.user # prepare the rendered page so it points them to open student/teacher reg's ctxt = {} userrole = {} regperm = None if user.isStudent(): userrole['name'] = 'Student' userrole['base'] = 'learn' userrole['reg'] = 'studentreg' regperm = 'Student/Classes' elif user.isTeacher(): userrole['name'] = 'Teacher' userrole['base'] = 'teach' userrole['reg'] = 'teacherreg' regperm = 'Teacher/Classes' ctxt['userrole'] = userrole if regperm: progs = list(Permission.program_by_perm(user,regperm)) else: progs = [] # If we have 1 program, automatically redirect to registration for that program. # Most chapters will want this, but it can be disabled by a Tag. if len(progs) == 1 and Tag.getBooleanTag('automatic_registration_redirect', default=True): ctxt['prog'] = progs[0] return HttpResponseRedirect(u'/%s/%s/%s' % (userrole['base'], progs[0].getUrlBase(), userrole['reg'])) else: if len(progs) > 0: # Sort available programs newest first progs.sort(key=lambda x: -x.id) ctxt['progs'] = progs ctxt['prog'] = progs[0] return render_to_response('users/profile_complete.html', request, ctxt)
def render_class_core(cls): """Render non-user-specific parts of a class for the catalog.""" prog = cls.parent_program scrmi = prog.studentclassregmoduleinfo colorstring = prog.getColor() if colorstring is not None: colorstring = ' background-color:#' + colorstring + ';' # Allow tag configuration of whether class descriptions get collapsed # when the class is full (default: yes) collapse_full = Tag.getBooleanTag('collapse_full_classes', prog, True) return { 'class': cls, 'collapse_full': collapse_full, 'colorstring': colorstring, 'show_enrollment': scrmi.visible_enrollments, 'show_emailcodes': scrmi.show_emailcodes, 'show_meeting_times': scrmi.visible_meeting_times }
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 phase_2(self): """Testing phase 2, where user provides info, and we make the account""" url = "/myesp/register/" if Tag.getBooleanTag("ask_about_duplicate_accounts", default=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 AccountCreationTest(TestCase): def setUp(self): user_role_setup() def test_phase_1(self): #There's a tag that affects phase 1 so we put the tests into a function #and call it twice here Tag.setTag('ask_about_duplicate_accounts',value='true') self.phase_1() Tag.setTag('ask_about_duplicate_accounts',value='false') self.phase_1() 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":"*****@*****.**", "confirm_email":"*****@*****.**"}) if not Tag.getBooleanTag('ask_about_duplicate_accounts', default=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":"*****@*****.**", "confirm_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":"*****@*****.**", "confirm_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":"*****@*****.**", "confirm_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":"*****@*****.**", "confirm_email":"*****@*****.**","do_reg_no_really":""},follow=True) self.assertContains(response4, "*****@*****.**") def test_phase_2(self): #similarly to phase_1, call helper function twice with tag settings Tag.setTag('require_email_validation',value='True') self.phase_2() Tag.setTag('require_email_validation',value='False') self.phase_2() def phase_2(self): """Testing phase 2, where user provides info, and we make the account""" url = "/myesp/register/" if Tag.getBooleanTag("ask_about_duplicate_accounts", default=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") if not Tag.getBooleanTag('require_email_validation', default=False): return self.assertFalse(u.is_active) self.assertTrue("_" in u.password) self.assertEqual(len(mail.outbox),1) self.assertEqual(len(mail.outbox[0].to),1) self.assertEqual(mail.outbox[0].to[0],u.email) #note: will break if the activation email is changed too much import re match = re.search("\?username=(?P<user>[^&]*)&key=(?P<key>\d+)",mail.outbox[0].body) self.assertEqual(match.group("user"),u.username) self.assertEqual(match.group("key"),u.password.rsplit("_")[-1])
def testBooleanTag(self): '''Test the logic of getBooleanTag in a bunch of different conditions, assuming that the underlying getProgramTag works.''' # Dump any existing Tag cache Tag._getTag.delete_all() self.assertFalse(Tag.getBooleanTag("test_bool")) self.assertFalse(Tag.getBooleanTag("test_bool")) self.assertFalse(Tag.getBooleanTag("test_bool", program=None)) self.assertFalse(Tag.getBooleanTag("test_bool", program=None)) self.assertFalse(Tag.getBooleanTag("test_bool", program=self.program)) self.assertFalse(Tag.getBooleanTag("test_bool", program=self.program)) for b in [True,False]: self.assertEqual(Tag.getBooleanTag("test_bool",default=b),b) self.assertEqual(Tag.getBooleanTag("test_bool",default=b),b) self.assertEqual(Tag.getBooleanTag("test_bool",program=None,default=b),b) self.assertEqual(Tag.getBooleanTag("test_bool",program=None,default=b),b) self.assertEqual(Tag.getBooleanTag("test_bool",program=self.program,default=b),b) self.assertEqual(Tag.getBooleanTag("test_bool",program=self.program,default=b),b) for true_val in [True,"True","true","1",1]: Tag.setTag("test_bool",target=self.program,value=true_val) self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program), True) self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program), True) for b in [True,False]: self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program, default=b), True) self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program, default=b), True) for false_val in [False,"False","false","0",0]: Tag.setTag("test_bool",target=self.program,value=false_val) self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program), False) self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program), False) for b in [True,False]: self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program, default=b), False) self.assertEqual(Tag.getBooleanTag("test_bool", program=self.program, default=b), False)
def testBooleanTag(self): '''Test the logic of getBooleanTag in a bunch of different conditions, assuming that the underlying getProgramTag works.''' # Dump any existing Tag cache Tag._getTag.delete_all() self.assertFalse(Tag.getBooleanTag("test_bool")) self.assertFalse(Tag.getBooleanTag("test_bool")) self.assertFalse(Tag.getBooleanTag("test_bool", program=None)) self.assertFalse(Tag.getBooleanTag("test_bool", program=None)) self.assertFalse(Tag.getBooleanTag("test_bool", program=self.program)) self.assertFalse(Tag.getBooleanTag("test_bool", program=self.program)) for b in [True, False]: self.assertEqual(Tag.getBooleanTag("test_bool", default=b), b) self.assertEqual(Tag.getBooleanTag("test_bool", default=b), b) self.assertEqual( Tag.getBooleanTag("test_bool", program=None, default=b), b) self.assertEqual( Tag.getBooleanTag("test_bool", program=None, default=b), b) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program, default=b), b) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program, default=b), b) for true_val in [True, "True", "true", "1", 1]: Tag.setTag("test_bool", target=self.program, value=true_val) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program), True) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program), True) for b in [True, False]: self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program, default=b), True) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program, default=b), True) for false_val in [False, "False", "false", "0", 0]: Tag.setTag("test_bool", target=self.program, value=false_val) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program), False) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program), False) for b in [True, False]: self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program, default=b), False) self.assertEqual( Tag.getBooleanTag("test_bool", program=self.program, default=b), False)
reg_form = TeacherOpenClassRegForm(self.crmi) # Provide initial forms: a request for each provided type, but no requests for new types. resource_formset = ResourceRequestFormSet( resource_type=resource_types, prefix='request') context['tl'] = 'teach' context['one'] = one context['two'] = two context['form'] = reg_form context['formset'] = resource_formset context['resource_types'] = self.program.getResourceTypes( include_classroom=True) context['classroom_form_advisories'] = 'classroom_form_advisories' if self.program.grade_max - self.program.grade_min >= 4: context['grade_range_popup'] = Tag.getBooleanTag( 'grade_range_popup', self.program, default=True) else: context['grade_range_popup'] = False if newclass is None: context['addoredit'] = 'Add' else: context['addoredit'] = 'Edit' context['classes'] = { 0: { 'type': 'class', 'link': 'makeaclass', 'reg_open': self.class_reg_is_open(), }, 1: {
def fillslot(self, request, tl, one, two, module, extra, prog): """ Display the page to fill the timeslot for a program """ from esp.cal.models import Event try: extra = int(extra) except: raise ESPError( False), 'Please use the link at the main registration page.' user = ESPUser(request.user) ts = Event.objects.filter(id=extra) if len(ts) < 1: raise Http404() ts = ts[0] prereg_url = self.program.get_learn_url() + 'addclass/' user_grade = user.getGrade(self.program) user.updateOnsite(request) is_onsite = user.isOnsite(self.program) # Override both grade limits and size limits during onsite registration if is_onsite and not request.GET.has_key('filter'): classes = list(ClassSubject.objects.catalog(self.program, ts)) else: classes = filter( lambda c: c.grade_min <= user_grade and c.grade_max >= user_grade, list(ClassSubject.objects.catalog(self.program, ts))) if Tag.getBooleanTag('hide_full_classes', prog, default=False): classes = filter( lambda c: not c.isFull(timeslot=ts, ignore_changes=True), classes) if user_grade != 0: classes = filter( lambda c: c.grade_min <= user_grade and c.grade_max >= user_grade, classes) classes = filter(lambda c: not c.isRegClosed(), classes) # Sort class list classes = sorted(classes, key=lambda cls: cls.num_students() - cls.capacity) classes = sorted(classes, key=lambda cls: cls.category.category) categories = {} for cls in classes: categories[cls.category_id] = { 'id': cls.category_id, 'category': cls.category_txt if hasattr(cls, 'category_txt') else cls.category.category } return render_to_response( self.baseDir() + 'fillslot.html', request, (prog, tl), { 'classes': classes, 'one': one, 'two': two, 'categories': categories.values(), 'timeslot': ts, 'prereg_url': prereg_url })
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 __init__(self, *args, **kwargs): super(UserContactForm, self).__init__(*args, **kwargs) if not Tag.getBooleanTag('request_student_phonenum', default=True): del self.fields['phone_day'] if not Tag.getBooleanTag('text_messages_to_students'): del self.fields['receive_txt_message']
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 __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 Tag.getTag('grade_ranges'): grade_ranges = json.loads(Tag.getTag('grade_ranges')) self.fields['grade_range'].choices = [(range,str(range[0]) + " - " + str(range[1])) for range in grade_ranges] self.fields['grade_range'].required = True hide_field( self.fields['grade_min'] ) self.fields['grade_min'].required = False hide_field( self.fields['grade_max'] ) self.fields['grade_max'].required = False else: hide_field( self.fields['grade_range'] ) 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. # TODO(benkraft): Is there a reason not to allow this on all fields? custom_helptext_fields = [ 'duration', 'class_size_max', 'num_sections', 'requested_room', 'message_for_directors', 'purchase_requests', 'class_info', 'grade_max', 'grade_min'] + 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')) # Get class_style_choices from tag, otherwise hide the field if Tag.getTag('class_style_choices'): self.fields['class_style'].choices = json.loads(Tag.getTag('class_style_choices')) self.fields['class_style'].required = True else: hide_field(self.fields['class_style'])
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 availabilityForm(self, request, tl, one, two, prog, teacher, isAdmin): time_options = self.program.getTimeSlots(types=[self.event_type()]) # Group contiguous blocks if not Tag.getBooleanTag('availability_group_timeslots', default=True): time_groups = [list(time_options)] else: time_groups = Event.group_contiguous(list(time_options)) blank = False available_slots = teacher.getAvailableTimes(self.program, True) # must set the ignore_classes=True parameter above, otherwise when a teacher tries to edit their # availability, it will show their scheduled times as unavailable. # Fetch the timeslots the teacher is scheduled in and grey them out. # If we found a timeslot that they are scheduled in but is not available, show a warning. taken_slots = [] avail_and_teaching = [] user_sections = teacher.getTaughtSections(self.program) conflict_found = False for section in user_sections: for timeslot in section.get_meeting_times(): taken_slots.append(timeslot) if timeslot not in available_slots: conflict_found = True else: avail_and_teaching.append(timeslot) if request.method == 'POST': # Process form post_vars = request.POST # Reset teacher's availability teacher.clearAvailableTimes(self.program) # But add back in the times they're teaching # because those aren't submitted with the form for timeslot in avail_and_teaching: teacher.addAvailableTime(self.program, timeslot) # Add in resources for the checked available times. timeslot_ids = map(int, post_vars.getlist('timeslots')) timeslots = Event.objects.filter( id__in=timeslot_ids).order_by('start') missing_tsids = set(timeslot_ids) - set(x.id for x in timeslots) if missing_tsids: raise ESPError( 'Received requests for the following timeslots that don\'t exist: %s' % str(list(sorted(missing_tsids))), log=False) blank = (not (bool(len(timeslot_ids) + len(avail_and_teaching)))) if not blank: for timeslot in timeslots: teacher.addAvailableTime(self.program, timeslot) # Send an e-mail showing availability to the teacher (and the archive) ccc = ClassCreationController(self.program) ccc.send_availability_email(teacher) if isAdmin: # Return to the relevant check_availability page return HttpResponseRedirect( '/manage/%s/%s/check_availability?user=%s' % (one, two, teacher.id)) else: # Return to the main registration page return self.goToCore(tl) # Show new form if not (len(available_slots) or blank): # I'm not sure whether or not we want the "or blank" # If they didn't enter anything, make everything checked by default. available_slots = self.program.getTimeSlots( types=[self.event_type()]) # The following 2 lines mark the teacher as always available. This # is sometimes helpful, but not usually the desired behavior. # for a in available_slots: # teacher.addAvailableTime(self.program, a) context = { 'groups': [{ 'selections': [{ 'checked': (t in available_slots), 'taken': (t in taken_slots), 'slot': t } for t in group] } for group in time_groups] } context['num_groups'] = len(context['groups']) context['prog'] = self.program context['is_overbooked'] = ( not self.isCompleted() and (teacher.getTaughtTime(self.program) > timedelta(0))) context['submitted_blank'] = blank context['conflict_found'] = conflict_found context['teacher_user'] = teacher return render_to_response(self.baseDir() + 'availability_form.html', request, context)
def registration_redirect(request): """ A view which returns: - A redirect to the currently open registration if exactly one registration is open - A list of open registration links otherwise """ from esp.users.models import ESPUser, UserBit from esp.program.models import Program # Make sure we have an ESPUser user = ESPUser(request.user) # prepare the rendered page so it points them to open student/teacher reg's ctxt = {} userrole = {} regverb = None if user.isStudent(): userrole['name'] = 'Student' userrole['base'] = 'learn' userrole['reg'] = 'studentreg' regverb = GetNode('V/Deadline/Registration/Student/Classes/OneClass') elif user.isTeacher(): userrole['name'] = 'Teacher' userrole['base'] = 'teach' userrole['reg'] = 'teacherreg' regverb = GetNode('V/Deadline/Registration/Teacher/Classes') else: # Default to student registration (this will only show if the program # is found via the 'allowed_student_types' Tag) userrole['name'] = user.getUserTypes()[0] userrole['base'] = 'learn' userrole['reg'] = 'studentreg' ctxt['userrole'] = userrole ctxt['navnode'] = GetNode('Q/Web/myesp') if regverb: progs_userbit = list( UserBit.find_by_anchor_perms(Program, user=user, verb=regverb)) else: progs_userbit = [] progs_tag = list(t.target \ for t in Tag.objects.filter(key = "allowed_student_types").select_related() \ if isinstance(t.target, Program) \ and (set(user.getUserTypes()) & set(t.value.split(",")))) progs = set(progs_userbit + progs_tag) nextreg = UserBit.objects.filter( user__isnull=True, verb=regverb, startdate__gt=datetime.datetime.now()).order_by('startdate') progs = list(progs) # If we have 1 program, automatically redirect to registration for that program. # Most chapters will want this, but it can be disabled by a Tag. if len(progs) == 1 and Tag.getBooleanTag('automatic_registration_redirect', default=True): ctxt['prog'] = progs[0] ctxt['navnode'] = progs[0].anchor return HttpResponseRedirect( u'/%s/%s/%s' % (userrole['base'], progs[0].getUrlBase(), userrole['reg'])) else: if len(progs) > 0: # Sort available programs newest first progs.sort(key=lambda x: -x.id) ctxt['progs'] = progs ctxt['prog'] = progs[0] ctxt['nextreg'] = list(nextreg) return render_to_response('users/profile_complete.html', request, GetNode('Q/Web'), ctxt)
def catalog_render(self, request, tl, one, two, module, extra, prog, timeslot=None): """ Return the program class catalog """ # using .extra() to select all the category text simultaneously classes = ClassSubject.objects.catalog(self.program) categories = {} for cls in classes: categories[cls.category_id] = { 'id': cls.category_id, 'category': cls.category_txt if hasattr(cls, 'category_txt') else cls.category.category } # Allow tag configuration of whether class descriptions get collapsed # when the class is full (default: yes) collapse_full = Tag.getBooleanTag('collapse_full_classes', prog, True) context = { 'classes': classes, 'one': one, 'two': two, 'categories': categories.values(), 'collapse_full': collapse_full } scrmi = prog.studentclassregmoduleinfo context['register_from_catalog'] = scrmi.register_from_catalog prog_color = prog.getColor() collapse_full_classes = Tag.getBooleanTag('collapse_full_classes', prog, True) class_blobs = [] category_header_str = """<hr size="1"/> <a name="cat%d"></a> <p style="font-size: 1.2em;" class="category"> %s </p> <p class="linktop"> <a href="#top">[ Return to Category List ]</a> </p> """ class_category_id = None for cls in classes: if cls.category.id != class_category_id: class_category_id = cls.category.id class_blobs.append(category_header_str % (class_category_id, cls.category.category)) class_blobs.append(render_class_direct(cls)) class_blobs.append('<br />') context['class_descs'] = ''.join(class_blobs) # Include the program explicitly; this is a cached page, without RequestContext context['program'] = self.program return render_to_response(self.baseDir() + 'catalog.html', request, context, use_request_context=False)
def require_auth(self): return Tag.getBooleanTag('volunteer_require_auth', self.program, default=False)