def rapidcheckin(self, request, tl, one, two, module, extra, prog): context = {} if request.method == 'POST': # Handle submission of student form = OnSiteRapidCheckinForm(request.POST) if form.is_valid(): student = ESPUser(form.cleaned_data['user']) # Check that this is a student user who is not also teaching (e.g. an admin) if student.isStudent() and student not in self.program.teachers()['class_approved']: recs = Record.objects.filter(user=student, event="attended", program=prog) if not recs.exists(): rec, created = Record.objects.get_or_create(user=student, event="attended", program=prog) context['message'] = '%s %s marked as attended.' % (student.first_name, student.last_name) if request.is_ajax(): return self.ajax_status(request, tl, one, two, module, extra, prog, context) else: context['message'] = '%s %s is not a student and has not been checked in' % (student.first_name, student.last_name) if request.is_ajax(): return self.ajax_status(request, tl, one, two, module, extra, prog, context) else: form = OnSiteRapidCheckinForm() context['module'] = self context['form'] = form return render_to_response(self.baseDir()+'ajaxcheckin.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 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 edit_profile(request, module): curUser = ESPUser(request.user) if curUser.isStudent(): return profile_editor(request, None, True, 'student') elif curUser.isTeacher(): return profile_editor(request, None, True, 'teacher') elif curUser.isGuardian(): return profile_editor(request, None, True, 'guardian') elif curUser.isEducator(): return profile_editor(request, None, True, 'educator') else: user_types = UserBit.valid_objects().filter(verb__parent=GetNode("V/Flags/UserRole")).select_related().order_by('-id') return profile_editor(request, None, True, user_types[0].verb.name if user_types else '')
def edit_profile(request, module): curUser = ESPUser(request.user) if curUser.isStudent(): return profile_editor(request, None, True, 'student') elif curUser.isTeacher(): return profile_editor(request, None, True, 'teacher') elif curUser.isGuardian(): return profile_editor(request, None, True, 'guardian') elif curUser.isEducator(): return profile_editor(request, None, True, 'educator') else: user_types = curUser.groups.all().order_by('-id') return profile_editor(request, None, True, user_types[0].name if user_types else '')
def get_msg_vars(self, user, key): user = ESPUser(user) if key == 'diag_sat_scores' or key == 'old_sat_scores' or key == 'prac_sat_scores': test_type = key.split('_')[0] if user.isStudent(): foo = SATPrepRegInfo.getLastForProgram(user, self.program) scores = 'Your %s SAT scores:\n' % { 'prac': 'practice', 'diag': 'diagnostic', 'old': 'original' }[test_type] for test in ['Math', 'Verbal', 'Writing']: curscore = foo.__dict__['%s_%s_score' % (test_type, test[0:4].lower())] if curscore is None or curscore < 200 or curscore > 800: scores += '%s: Not Available\n' % test else: scores += '%s: %s\n' % (test, curscore) return scores return ''
def profile_editor(request, prog_input=None, responseuponCompletion = True, role=''): """ Display the registration profile page, the page that contains the contact information for a student, as attached to a particular program """ from esp.users.models import K12School from esp.web.views.main import registration_redirect STUDREP_VERB = GetNode('V/Flags/UserRole/StudentRep') STUDREP_QSC = GetNode('Q') if prog_input is None: prog = None navnode = GetNode('Q/Web/myesp') else: prog = prog_input navnode = prog.anchor curUser = request.user context = {'logged_in': request.user.is_authenticated() } context['user'] = request.user context['program'] = prog curUser = ESPUser(curUser) curUser.updateOnsite(request) # Get the profile form from the user's type, although we need to handle # a couple of extra possibilities for the 'role' variable. user_types = ESPUser.getAllUserTypes() additional_types = [['', {'label': 'Not specified', 'profile_form': 'UserContactForm'}], ['Administrator', {'label': 'Administrator', 'profile_form': 'UserContactForm'}], ] additional_type_labels = [x[0] for x in additional_types] # Handle all-lowercase versions of role being passed in by calling title() user_type_labels = [x[0] for x in user_types] if role.title() in user_type_labels: target_type = user_types[user_type_labels.index(role.title())][1] else: target_type = additional_types[additional_type_labels.index(role.title())][1] mod = __import__('esp.users.forms.user_profile', (), (), target_type['profile_form']) FormClass = getattr(mod, target_type['profile_form']) context['profiletype'] = role if request.method == 'POST' and request.POST.has_key('profile_page'): form = FormClass(curUser, request.POST) # Don't suddenly demand an explanation from people who are already student reps if UserBit.objects.UserHasPerms(curUser, STUDREP_QSC, STUDREP_VERB): if hasattr(form, 'repress_studentrep_expl_error'): form.repress_studentrep_expl_error() if form.is_valid(): new_data = form.cleaned_data regProf = RegistrationProfile.getLastForProgram(curUser, prog) if regProf.id is None: old_regProf = RegistrationProfile.getLastProfile(curUser) else: old_regProf = regProf for field_name in ['address_zip','address_city','address_street','address_state']: if field_name in new_data and new_data[field_name] != getattr(old_regProf.contact_user,field_name,False): new_data['address_postal'] = '' if new_data['address_postal'] == '': new_data['address_postal'] = False regProf.contact_user = ContactInfo.addOrUpdate(regProf, new_data, regProf.contact_user, '', curUser) regProf.contact_emergency = ContactInfo.addOrUpdate(regProf, new_data, regProf.contact_emergency, 'emerg_') if new_data.has_key('dietary_restrictions') and new_data['dietary_restrictions']: regProf.dietary_restrictions = new_data['dietary_restrictions'] if role == 'student': regProf.student_info = StudentInfo.addOrUpdate(curUser, regProf, new_data) regProf.contact_guardian = ContactInfo.addOrUpdate(regProf, new_data, regProf.contact_guardian, 'guard_') elif role == 'teacher': regProf.teacher_info = TeacherInfo.addOrUpdate(curUser, regProf, new_data) elif role == 'guardian': regProf.guardian_info = GuardianInfo.addOrUpdate(curUser, regProf, new_data) elif role == 'educator': regProf.educator_info = EducatorInfo.addOrUpdate(curUser, regProf, new_data) blah = regProf.__dict__ regProf.save() curUser.first_name = new_data['first_name'] curUser.last_name = new_data['last_name'] curUser.email = new_data['e_mail'] curUser.save() if responseuponCompletion == True: return registration_redirect(request) else: return True else: # Force loading the school back in if possible... replacement_data = form.data.copy() try: replacement_data['k12school'] = form.fields['k12school'].clean(form.data['k12school']).id except: pass form = FormClass(curUser, replacement_data) else: if prog_input is None: regProf = RegistrationProfile.getLastProfile(curUser) else: regProf = RegistrationProfile.getLastForProgram(curUser, prog) if regProf.id is None: regProf = RegistrationProfile.getLastProfile(curUser) new_data = {} if curUser.isStudent(): new_data['studentrep'] = (UserBit.objects.filter(user = curUser, verb = STUDREP_VERB, qsc = STUDREP_QSC).count() > 0) new_data['first_name'] = curUser.first_name new_data['last_name'] = curUser.last_name new_data['e_mail'] = curUser.email new_data = regProf.updateForm(new_data, role) if request.session.has_key('birth_month') and request.session.has_key('birth_day'): new_data['dob'] = datetime.date(1994, int(request.session['birth_month']), int(request.session['birth_day'])) if request.session.has_key('school_id'): new_data['k12school'] = request.session['school_id'] # Set default values for state fields state_fields = ['address_state', 'emerg_address_state'] state_tag_map = {} for field in state_fields: state_tag_map[field] = 'local_state' form = FormClass(curUser, initial=new_data, tag_map=state_tag_map) context['request'] = request context['form'] = form return render_to_response('users/profile.html', request, navnode, context)
def survey_view(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = ESPUser(request.user) if (tl == 'teach' and not user.isTeacher()) or (tl == 'learn' and not user.isStudent()): raise ESPError( False ), 'You need to be a program participant (i.e. student or teacher, not parent or educator) to participate in this survey. Please contact the directors directly if you have additional feedback.' if request.GET.has_key('done'): return render_to_response('survey/completed_survey.html', request, {'prog': prog}) if tl == 'learn': event = "student_survey" else: event = "teacher_survey" if Record.user_completed(user, event, prog): raise ESPError( False ), "You've already filled out the survey. Thanks for responding!" surveys = prog.getSurveys().filter(category=tl).select_related() if request.REQUEST.has_key('survey_id'): try: s_id = int(request.REQUEST['survey_id']) surveys = surveys.filter( id=s_id ) # We want to filter, not get: ID could point to a survey that doesn't exist for this program, or at all except ValueError: pass if len(surveys) < 1: raise ESPError(False), "Sorry, no such survey exists for this program!" if len(surveys) > 1: return render_to_response( 'survey/choose_survey.html', request, { 'surveys': surveys, 'error': request.POST } ) # if request.POST, then we shouldn't have more than one survey any more... survey = surveys[0] if request.POST: response = SurveyResponse() response.survey = survey response.save() r = Record(user=user, event=event, program=prog, time=datetime.datetime.now()) r.save() response.set_answers(request.POST, save=True) return HttpResponseRedirect(request.path + "?done") else: questions = survey.questions.filter(per_class=False).order_by('seq') perclass_questions = survey.questions.filter(per_class=True) classes = sections = timeslots = [] if tl == 'learn': classes = user.getEnrolledClasses(prog, request) timeslots = prog.getTimeSlots().order_by('start') for ts in timeslots: # The order by string really means "title" ts.classsections = prog.sections().filter( meeting_times=ts).exclude( meeting_times__start__lt=ts.start).order_by( 'parent_class__title').distinct() for sec in ts.classsections: if user in sec.students(): sec.selected = True elif tl == 'teach': classes = user.getTaughtClasses(prog) sections = user.getTaughtSections(prog).order_by( 'parent_class__title') context = { 'survey': survey, 'questions': questions, 'perclass_questions': perclass_questions, 'program': prog, 'classes': classes, 'sections': sections, 'timeslots': timeslots, } return render_to_response('survey/survey.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)