def survey_review_single(request, tl, program, instance): """ View a single survey response. """ try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: #raise Http404 raise ESPError(), "Can't find the program %s/%s" % (program, instance) user = ESPUser(request.user) survey_response = None ints = request.REQUEST.items() if len(ints) == 1: srs = SurveyResponse.objects.filter(id=ints[0][0]) if len(srs) == 1: survey_response = srs[0] if survey_response is None: raise ESPError( False ), 'Ideally this page should give you some way to pick an individual response. For now I guess you should go back to <a href="review">reviewing the whole survey</a>.' if tl == 'manage' and user.isAdmin(prog): answers = survey_response.answers.order_by('content_type', 'object_id', 'question') classes_only = False other_responses = None elif tl == 'teach': subject_ct = ContentType.objects.get(app_label="program", model="classsubject") section_ct = ContentType.objects.get(app_label="program", model="classsection") class_ids = [x["id"] for x in user.getTaughtClasses().values('id')] section_ids = [x["id"] for x in user.getTaughtSections().values('id')] answers = survey_response.answers.filter( content_type__in=[subject_ct, section_ct], object_id__in=(class_ids + section_ids)).order_by( 'content_type', 'object_id', 'question') classes_only = True other_responses = SurveyResponse.objects.filter( answers__content_type=subject_ct, answers__object_id__in=class_ids).order_by('id').distinct() else: raise ESPError( False ), 'You need to be a teacher or administrator of this program to review survey responses.' context = { 'user': user, 'program': prog, 'response': survey_response, 'answers': answers, 'classes_only': classes_only, 'other_responses': other_responses } return render_to_response('survey/review_single.html', request, context)
def survey_review_single(request, tl, program, instance): """ View a single survey response. """ try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: #raise Http404 raise ESPError(), "Can't find the program %s/%s" % (program, instance) user = ESPUser(request.user) survey_response = None ints = request.REQUEST.items() if len(ints) == 1: srs = SurveyResponse.objects.filter(id=ints[0][0]) if len(srs) == 1: survey_response = srs[0] if survey_response is None: raise ESPError( False ), 'Ideally this page should give you some way to pick an individual response. For now I guess you should go back to <a href="review">reviewing the whole survey</a>.' if tl == 'manage' and user.isAdmin(prog.anchor): answers = survey_response.answers.order_by('anchor', 'question') classes_only = False elif tl == 'teach': class_anchors = [ x['anchor'] for x in user.getTaughtClasses().values('anchor') ] answers = survey_response.answers.filter( anchor__in=class_anchors).order_by('anchor', 'question') classes_only = True else: raise ESPError( False ), 'You need to be a teacher or administrator of this program to review survey responses.' context = { 'user': user, 'program': prog, 'response': survey_response, 'answers': answers, 'classes_only': classes_only } return render_to_response('survey/review_single.html', request, prog.anchor, context)
def get_survey_info(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = request.user if (tl == 'teach' and user.isTeacher()): surveys = prog.getSurveys().filter(category='learn').select_related() elif (tl == 'manage' and user.isAdmin(prog)): # Meerp, no problem... I took care of it. -Michael surveys = prog.getSurveys().select_related() if 'teacher_id' in request.GET: t_id = int(request.GET['teacher_id']) teachers = ESPUser.objects.filter(id=t_id) if len(teachers) > 0: user = teachers[0] if user.isTeacher(): surveys = prog.getSurveys().filter( category='learn').select_related() else: user = request.user else: raise ESPError( 'You need to be a teacher or administrator of this program to review survey responses.', log=False) if 'survey_id' in request.GET: try: s_id = int(request.GET['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("Sorry, no such survey exists for this program!", log=False) return (user, prog, surveys)
def csrf_failure(request, reason=""): """ View used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_REFERER c = { 'DEBUG': settings.DEBUG and request.user.isAdministrator(), 'reason': reason, 'no_referer': reason == REASON_NO_REFERER } # We wrap our custom csrf_failure in a try-block, and fall back to # Django's global default view in the case of an exception, since we need # to be able to reliably display the error message. try: from esp.web.util.main import render_to_response from esp.program.models import Program prog_re = r'^[-A-Za-z0-9_ ]+/([-A-Za-z0-9_ ]+)/([-A-Za-z0-9_ ]+)' match = re.match(prog_re, request.path) if match: one, two = match.groups() try: prog = Program.by_prog_inst(one, two) except Program.DoesNotExist: prog = None else: prog = None response = render_to_response('403_csrf_failure.html', request, c, prog=prog) response = HttpResponseForbidden(response.content, mimetype=response['Content-Type']) except Exception: response = django_csrf_failure(request, reason=reason) return response
def program(request, tl, one, two, module, extra = None): """ Return program-specific pages """ from esp.program.models import Program try: prog = Program.by_prog_inst(one, two) except Program.DoesNotExist: raise Http404("Program not found.") setattr(request, "program", prog) setattr(request, "tl", tl) if extra: setattr(request, "module", "%s/%s" % (module, extra)) else: setattr(request, "module", module) from esp.program.modules.base import ProgramModuleObj newResponse = ProgramModuleObj.findModule(request, tl, one, two, module, extra, prog) if newResponse: return newResponse raise Http404
def survey_review_single(request, tl, program, instance): """ View a single survey response. """ try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: #raise Http404 raise ESPError("Can't find the program %s/%s" % (program, instance)) user = request.user survey_response = None ints = request.GET.items() if len(ints) == 1: srs = SurveyResponse.objects.filter(id=ints[0][0]) if len(srs) == 1: survey_response = srs[0] if survey_response is None: raise ESPError('Ideally this page should give you some way to pick an individual response. For now I guess you should go back to <a href="review">reviewing the whole survey</a>.', log=False) if tl == 'manage' and user.isAdmin(prog): answers = survey_response.answers.order_by('content_type','object_id', 'question') classes_only = False other_responses = None elif tl == 'teach': subject_ct=ContentType.objects.get(app_label="program",model="classsubject") section_ct=ContentType.objects.get(app_label="program",model="classsection") class_ids = [x["id"] for x in user.getTaughtClasses().values('id')] section_ids = [x["id"] for x in user.getTaughtSections().values('id')] answers = survey_response.answers.filter(content_type__in=[subject_ct, section_ct], object_id__in=(class_ids+section_ids)).order_by('content_type','object_id', 'question') classes_only = True other_responses = SurveyResponse.objects.filter(answers__content_type=subject_ct, answers__object_id__in=class_ids).order_by('id').distinct() else: raise ESPError('You need to be a teacher or administrator of this program to review survey responses.', log=False) context = {'user': user, 'program': prog, 'response': survey_response, 'answers': answers, 'classes_only': classes_only, 'other_responses': other_responses } return render_to_response('survey/review_single.html', request, context)
def get_survey_info(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = request.user if (tl == 'teach' and user.isTeacher()): surveys = prog.getSurveys().filter(category = 'learn').select_related() elif (tl == 'manage' and user.isAdmin(prog)): # Meerp, no problem... I took care of it. -Michael surveys = prog.getSurveys().select_related() if 'teacher_id' in request.GET: t_id = int( request.GET['teacher_id'] ) teachers = ESPUser.objects.filter(id=t_id) if len(teachers) > 0: user = teachers[0] if user.isTeacher(): surveys = prog.getSurveys().filter(category = 'learn').select_related() else: user = request.user else: raise ESPError('You need to be a teacher or administrator of this program to review survey responses.', log=False) if 'survey_id' in request.GET: try: s_id = int( request.GET['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("Sorry, no such survey exists for this program!", log=False) return (user, prog, surveys)
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 top_classes(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = ESPUser(request.user) if (tl == 'manage' and user.isAdmin(prog)): surveys = prog.getSurveys().filter(category='learn').select_related() else: raise ESPError( False ), 'You need to be a teacher or administrator of this program to review survey responses.' 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 tl == 'manage': classes = prog.classes() rating_questions = survey.questions.filter( name__contains='overall rating') if len(rating_questions) < 1: raise ESPError( False ), 'Couldn\'t find an "overall rating" question in this survey.' rating_question = rating_questions[0] rating_cut = 0.0 try: rating_cut = float( rating_question.get_params()['number_of_ratings']) - 1 except ValueError: pass if request.REQUEST.has_key('rating_cut'): try: rating_cut = float(request.REQUEST['rating_cut']) except ValueError: pass num_cut = 1 if request.REQUEST.has_key('num_cut'): try: num_cut = int(request.REQUEST['num_cut']) except ValueError: pass categories = prog.class_categories.all().order_by('category') subject_ct = ContentType.objects.get(app_label="program", model="classsubject") perclass_data = [] initclass_data = [{ 'class': x, 'ratings': [ x.answer for x in Answer.objects.filter(object_id=x.id, content_type=subject_ct, question=rating_question) ] } for x in classes] for c in initclass_data: c['numratings'] = len(c['ratings']) if c['numratings'] < num_cut: continue c['avg'] = sum(c['ratings']) * 1.0 / c['numratings'] if c['avg'] < rating_cut: continue teachers = list(c['class'].get_teachers()) c['teacher'] = teachers[0] c['numteachers'] = len(teachers) if c['numteachers'] > 1: c['coteachers'] = teachers[1:] del c['ratings'] perclass_data.append(c) context = { 'survey': survey, 'program': prog, 'perclass_data': perclass_data, 'rating_cut': rating_cut, 'num_cut': num_cut, 'categories': categories } return render_to_response('survey/top_classes.html', request, context)
def survey_view(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = request.user if (tl == 'teach' and not user.isTeacher()) or (tl == 'learn' and not user.isStudent()): raise ESPError('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.', log=False) if 'done' in request.GET: 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("You've already filled out the survey. Thanks for responding!", log=False) surveys = prog.getSurveys().filter(category = tl).select_related() if 'survey_id' in request.GET: try: s_id = int( request.GET['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("Sorry, no such survey exists for this program!", log=False) 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) enrolled_secs = user.getEnrolledSections(prog) 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 sec in enrolled_secs: 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 top_classes(request, tl, program, instance): try: prog = Program.by_prog_inst(program, instance) except Program.DoesNotExist: raise Http404 user = request.user if (tl == 'manage' and user.isAdmin(prog)): surveys = prog.getSurveys().filter(category = 'learn').select_related() else: raise ESPError('You need to be a teacher or administrator of this program to review survey responses.', log=False) if 'survey_id' in request.GET: try: s_id = int( request.GET['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('Sorry, no such survey exists for this program!', log=False) 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 tl == 'manage': classes = prog.classes() rating_questions = survey.questions.filter(name__contains='overall rating') if len(rating_questions) < 1: raise ESPError('Couldn\'t find an "overall rating" question in this survey.', log=False) rating_question = rating_questions[0] rating_cut = 0.0 try: rating_cut = float( rating_question.get_params()['number_of_ratings'] ) - 1 except ValueError: pass if 'rating_cut' in request.GET: try: rating_cut = float( request.GET['rating_cut'] ) except ValueError: pass num_cut = 1 if 'num_cut' in request.GET: try: num_cut = int( request.GET['num_cut'] ) except ValueError: pass categories = prog.class_categories.all().order_by('category') subject_ct=ContentType.objects.get(app_label="program",model="classsubject") perclass_data = [] initclass_data = [ { 'class': x, 'ratings': [ x.answer for x in Answer.objects.filter(object_id=x.id, content_type=subject_ct, question=rating_question) ] } for x in classes ] for c in initclass_data: c['numratings'] = len(c['ratings']) if c['numratings'] < num_cut: continue c['avg'] = sum(c['ratings']) * 1.0 / c['numratings'] if c['avg'] < rating_cut: continue teachers = list(c['class'].get_teachers()) c['teacher'] = teachers[0] c['numteachers'] = len(teachers) if c['numteachers'] > 1: c['coteachers'] = teachers[1:] del c['ratings'] perclass_data.append(c) context = { 'survey': survey, 'program': prog, 'perclass_data': perclass_data, 'rating_cut': rating_cut, 'num_cut': num_cut, 'categories': categories } return render_to_response('survey/top_classes.html', request, context)
def classchangerequest(request, tl, one, two): from esp.program.models import Program, StudentAppResponse, StudentRegistration, RegistrationType from esp.program.models.class_ import * from urllib import quote try: prog = Program.by_prog_inst(one, two) #DataTree.get_by_uri(treeItem) except Program.DoesNotExist: raise Http404("Program not found.") if tl != "learn": raise Http404 if not request.user or not request.user.is_authenticated(): 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(prog): allowed_student_types = Tag.getTag("allowed_student_types", prog, 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, (prog, 'learn'), {}) errorpage = 'errors/program/wronggrade.html' verb_override = GetNode('V/Flags/Registration/GradeOverride') cur_grade = request.user.getGrade(prog) if (not UserBit.UserHasPerms(user = request.user, qsc = prog.anchor_id, verb = verb_override)) and (cur_grade != 0 and (cur_grade < prog.grade_min or \ cur_grade > prog.grade_max)): return render_to_response(errorpage, request, (prog, tl), {}) setattr(request, "program", prog) setattr(request, "tl", tl) setattr(request, "module", "classchangerequest") from django import forms from datetime import datetime from esp.utils.scheduling import getRankInClass timeslots = prog.getTimeSlots() sections = prog.sections().filter(status=10) enrollments = {} for timeslot in timeslots: try: enrollments[timeslot] = ClassSubject.objects.get( sections__studentregistration__relationship__name="Enrolled", sections__studentregistration__user=request.user, sections__meeting_times=timeslot, parent_program=prog, sections__studentregistration__end_date__gte=datetime.now()) except ClassSubject.DoesNotExist: enrollments[timeslot] = None context = {} context['timeslots'] = timeslots context['enrollments'] = enrollments context['user'] = request.user if 'success' in request.GET: context['success'] = True else: context['success'] = False if request.user.isStudent(): sections_by_slot = dict([(timeslot, [ (section, 1 == StudentRegistration.objects.filter( user=context['user'], section=section, relationship__name="Request", end_date__gte=datetime.now()).count()) for section in sections if section.get_meeting_times()[0] == timeslot and section.parent_class.grade_min <= request.user.getGrade( prog) <= section.parent_class.grade_max and section.parent_class not in enrollments.values() and getRankInClass(request.user, section) in (5, 10) ]) for timeslot in timeslots]) else: sections_by_slot = dict([(timeslot, [ (section, False) for section in sections if section.get_meeting_times()[0] == timeslot ]) for timeslot in timeslots]) fields = {} for i, timeslot in enumerate(sections_by_slot.keys()): choices = [('0', "I'm happy with my current enrollment.")] initial = '0' for section in sections_by_slot[timeslot]: choices.append( (section[0].emailcode(), section[0].emailcode() + ": " + section[0].title())) if section[1]: initial = section[0].emailcode() fields['timeslot_' + str(i + 1)] = forms.ChoiceField( label="Timeslot " + str(i + 1) + " (" + timeslot.pretty_time() + ")", choices=choices, initial=initial) form = type('ClassChangeRequestForm', (forms.Form, ), fields) context['form'] = form() if request.method == "POST": old_requests = StudentRegistration.objects.filter( user=context['user'], section__parent_class__parent_program=prog, relationship__name="Request", end_date__gte=datetime.now()) for r in old_requests: r.expire() form = form(request.POST) if form.is_valid(): for value in form.cleaned_data.values(): section = None for s in sections: if s.emailcode() == value: section = s break if not section: continue r = StudentRegistration.objects.get_or_create( user=context['user'], section=section, relationship=RegistrationType.objects.get_or_create( name="Request", category="student")[0])[0] r.end_date = datetime(9999, 1, 1, 0, 0, 0, 0) r.save() return HttpResponseRedirect(request.path.rstrip('/') + '/?success') else: return render_to_response('program/classchangerequest.html', request, (prog, tl), context)