示例#1
0
def retrieve_student_subjects(request):
    subject_list = {

    }
    response_array = []

    if request.method == 'GET':
        student = request.GET.get('student')
        print (student)
        try:
            s = Student.objects.get(id=student)
            c = s.current_class
            sect = s.current_section

            test_list = ClassTest.objects.filter(the_class=c, section=sect, is_completed=True)
            for test in test_list:
                subject = test.subject.subject_name
                subject_list['subject'] = subject
                d = dict(subject_list)
                response_array.append(d)
            try:
                parent_mobile = s.parent.parent_mobile1
                action = 'Retrieved Subject List for ' + s.fist_name + ' ' + s.last_name
                log_entry(parent_mobile, action, 'Normal', True)
            except Exception as e:
                print('unable to create logbook entry')
                print ('Exception 506 from parents views.py %s %s' % (e.message, type(e)))

            return JSONResponse(response_array, status=200)
        except Exception as e:
            print ('unable to retrieve list of subjects for ' + s.fist_name + ' ' + s.last_name)
            print ('Exception11 from parents views.py = %s (%s)' % (e.message, type(e)))
    return JSONResponse(response_array, status=201)
示例#2
0
def delete_bus_attendance1(request, att_type, d, m, y):
    response_data = {

    }
    if request.method == 'POST':
        the_date = date(int(y), int(m), int(d))

        data = json.loads(request.body)
        print ('attendance correction data=')
        print (data)
        for key in data:
            st = data[key]
            # check whether the absence for this student for this date has been already marked or not
            try:
                student = Student.objects.get(id=st)
                attendance_type = Attedance_Type.objects.get(route_type=att_type)
                q = Bus_Attendance.objects.filter(date=the_date, student=student, attendance_type=attendance_type)
                if q.count() > 0:
                    q.delete()
            except Exception as e:
                print ('unable to delete the bus attendance for ' + student.fist_name + ' ' + student.last_name)
                print ('Exception15 in bus_attendance views.py = %s (%s)' % (e.message, type(e)))
        response_data['status'] = 'success'

    return JSONResponse(response_data, status=200)
示例#3
0
    def post(self, request, *args, **kwargs):
        student_id = self.kwargs['student_id']
        student = Student.objects.get(id=student_id)
        test_id = self.kwargs['test_id']
        online_test = OnlineTest.objects.get(id=test_id)

        try:
            data = json.loads(request.body)
            print('json=')
            print(data)
            submitted_via = data['submitted_via']
            print('this test submitted via %s' % submitted_via)
        except Exception as e:
            print('exception 17052020-B from online_test views.py %s %s' %
                  (e.message, type(e)))
            print('this test is submitted via smartphone')
            submitted_via = 'smartphone'

        context_dict = {}
        try:
            attempted = StudentTestAttempt.objects.get(student=student,
                                                       online_test=online_test)
            print('attempt recorded')
        except Exception as e:
            print('exception 22042020-B from online_test viws.py %s %s' %
                  (e.message, type(e)))
            print('recording attempt for the first time')
            attempted = StudentTestAttempt(student=student,
                                           online_test=online_test)
            attempted.submitted_via = submitted_via
            attempted.save()

        return JSONResponse(context_dict, status=200)
示例#4
0
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        school_id = data['school_id']
        school = School.objects.get(id=school_id)
        the_class = data['the_class']
        c = Class.objects.get(school=school, standard=the_class)
        section = data['section']
        s = Section.objects.get(school=school, section=section)
        teacher_id = data['teacher_id']
        t = Teacher.objects.get(id=teacher_id)

        try:
            ct = ClassTeacher.objects.get(school=school, standard=c, section=s)
            cct = ct.class_teacher  # current class teacher?
            ct.class_teacher = t
            ct.save()
            message = cct.first_name + ' ' + cct.last_name + ' was the Class Teacher for class '
            message += the_class + ' ' + section + '. Now the new Class Teacher is '
            message += '%s %s' % (t.first_name, t.last_name)
            print(message)
            response_dict = {'message': message}
            response_dict['status'] = 'success'
            return JSONResponse(response_dict, status=200)
        except Exception as e:
            print('Exception 04022020-A from teachers views.py = %s (%s) ' % (e.message, type(e)))
            print('no Class Teacher was set for class ' + the_class + ' ' + section + '. Setting now...')
            try:
                ct = ClassTeacher()
                ct.school = school
                ct.standard = c
                ct.section = s
                ct.class_teacher = t
                ct.save()
                message = '%s is now assigned as Class Teacher for class ' % t
                message += the_class + ' ' + section
                print(message)
                response_dict['message'] = message
                response_dict['status'] = 'success'
                return JSONResponse(response_dict, status=200)
            except Exception as e:
                print ('Exception 04022020-B from teachers views.py = %s (%s) ' % (e.message, type(e)))
                error_message = 'failed to set %s as Class Teacher for class: ' % t
                error_message += the_class + ' ' + section
                print(error_message)
                response_dict['error_message'] = error_message
                return JSONResponse(response_dict, status=201)
示例#5
0
def retrieve_stu_sub_marks_history(request, subject):
    marks_history = {

    }
    response_array = []

    if request.method == 'GET':
        student = request.GET.get('student')

        try:

            s = Student.objects.get(id=student)
            sub = Subject.objects.get(school=s.school, subject_name=subject)
            c = s.current_class
            sect = s.current_section

            test_list = ClassTest.objects.filter(the_class=c, section=sect, subject=sub, is_completed=True). \
                order_by('date_conducted')
            for test in test_list:
                marks_history['date'] = test.date_conducted

                test_result = TestResults.objects.get(class_test=test, student=s)
                if test.grade_based:
                    marks_history['max_marks'] = 'Grade Based'
                    marks_history['marks'] = test_result.grade
                else:
                    marks_history['max_marks'] = test.max_marks
                    marks_history['marks'] = test_result.marks_obtained
                d = dict(marks_history)
                response_array.append(d)
            try:
                parent_mobile = s.parent.parent_mobile1
                action = 'Retrieved ' + sub.subject_name + ' marks history for ' + s.fist_name + ' ' + s.last_name
                log_entry(parent_mobile, action, 'Normal', True)
            except Exception as e:
                print('unable to create logbook entry')
                print ('Exception 507 from parents views.py %s %s' % (e.message, type(e)))

            return JSONResponse(response_array, status=200)
        except Exception as e:
            print ('Exception 12 from parents views.py = %s (%s)' % (e.message, type(e)))
            print ('unable to retrieve ' + sub.subject_name + ' marks history for '
                   + s.fist_name + ' ' + s.last_name)

    return JSONResponse(response_array, status=201)
示例#6
0
 def delete(self, request, *args, **kwargs):
     context_dict = {}
     image_id = self.kwargs["image_id"]
     try:
         media = ImageVideo.objects.get(id=image_id)
         media.active_status = False
         media.save()
         print('media marked inactive')
         context_dict['message'] = 'Media deleted'
         context_dict['status'] = 'success'
         return JSONResponse(context_dict, status=200)
     except Exception as e:
         print('exception 13082019-A from pic_share views.py %s %s' %
               (e.message, type(e)))
         message = 'failed to delete media. Please try again.'
         context_dict['message'] = message
         context_dict['status'] = 'failed'
         return JSONResponse(context_dict, status=201)
示例#7
0
def attendance_taken_earlier(request, school_id, rout, d, m, y):
    if request.method == 'GET':
        return_data = {

        }
        the_date = date(int(y), int(m), int(d))
        try:
            school = School.objects.get(id=school_id)
            r = Bus_Rout.objects.get(school=school, bus_root=rout)

            q = BusAttendanceTaken.objects.filter(date=the_date, rout=r)
            if 0 == q.count():
                return_data['taken_earlier'] = False
            else:
                return_data['taken_earlier'] = True
            return JSONResponse(return_data, status=200)
        except Exception as e:
            print ('unable to check whether bus attendance was taken on ' + rout + ' on ' + str(the_date))
            print ('Exception13 in bus_attendance views.py = %s (%s)' % (e.message, type(e)))
    return JSONResponse(return_data, status=201)
示例#8
0
def delete_teacher(request):
    response_dict = {

    }

    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            teacher_id = data['teacher_id']
            teacher = Teacher.objects.get(id=teacher_id)
            teacher.active_status = False
            teacher.save()
            response_dict['status'] = 'success'
            return JSONResponse(response_dict, status=200)
        except Exception as e:
            print('Exception 80 from teachers views.py = %s (%s) ' % (e.message, type(e)))
            error_message = 'Failed to set active_status of ' + teacher.first_name + ' ' \
                            + teacher.last_name + ' to False'
            teacher['status'] = 'failed'
            teacher['error_message'] = error_message
            return JSONResponse(response_dict, status=201)
示例#9
0
    def get(self, request, *args, **kwargs):
        student_id = self.kwargs['student_id']
        student = Student.objects.get(id=student_id)
        test_id = self.kwargs['test_id']
        online_test = OnlineTest.objects.get(id=test_id)

        context_dict = {}
        if StudentTestAttempt.objects.filter(student=student,
                                             online_test=online_test).exists():
            context_dict['attempted'] = 'true'
        else:
            context_dict['attempted'] = 'false'
        return JSONResponse(context_dict, status=200)
示例#10
0
def delete_attendance2(request, school_id, the_class, section, subject, d, m,
                       y):
    response_data = {}
    if request.method == 'POST':
        school = School.objects.get(id=school_id)
        # all of the above except date are foreign key in Attendance model. Hence we need to get the actual object
        c = Class.objects.get(school=school, standard=the_class)
        s = Section.objects.get(school=school, section=section)
        sub = Subject.objects.get(school=school, subject_name=subject)

        the_date = date(int(y), int(m), int(d))
        print(the_date)
        data = json.loads(request.body)
        print('correction list=')
        print(data)
        for key in data:
            student_id = data[key]
            student = Student.objects.get(id=student_id)

            # check to see if absence for this student for this date, class, section and subject has already been marked
            try:
                q = Attendance.objects.filter(date=the_date,
                                              the_class=c,
                                              section=s,
                                              subject=sub,
                                              student=student)
                print(q.count())
                # make an entry to database only it is a fresh entry
                if q.count() > 0:
                    try:
                        q1 = q[:1].get()
                        teacher = q1.taken_by.email
                        q.delete()

                        action = 'Deleted a previously taken attendance for ' +\
                                 student.fist_name + ' ' + student.last_name
                        log_entry(teacher, action, "Normal", True)
                    except Exception as e:
                        print(
                            'Exception 7 from attendance views.py = %s (%s)' %
                            (e.message, type(e)))

            except Exception as e:
                print('Exception 9 from attendance views.py = %s (%s)' %
                      (e.message, type(e)))

        # this view is being called from mobile. We use dummy template so that we dont' run into exception
        # return render(request, 'classup/dummy.html')
        response_data['status'] = 'success'
        return JSONResponse(response_data, status=200)
示例#11
0
    def post(self, request):
        context_dict = {}
        schools = School.objects.filter()
        first_april = date(int(2019), int(4), int(1))
        thirty_sep = date(int(2019), int(9), int(30))
        thirty_march = date(int(2020), int(3), int(31))
        for school in schools:
            print('now dealing with students of %s' % school)
            students = Student.objects.filter(school=school)
            for student in students:
                total_days = AttendanceTaken.objects.filter(
                    the_class=student.current_class,
                    date__gte=first_april,
                    date__lte=thirty_march,
                    section=student.current_section).count()
                print('total working days for class %s %s of %s: %i' %
                      (student.current_class.standard,
                       student.current_section.section, school, total_days))
                absent_days = Attendance.objects.filter(
                    student=student, date__gte=first_april).count()
                present_days = total_days - absent_days
                print('%s attendance = %i/%i. Will now store to database' %
                      (student, present_days, total_days))

                try:
                    entry = IndividualAttendance.objects.get(student=student)
                    entry.total_days = total_days
                    entry.present_days = present_days
                    entry.absent_days = absent_days
                    entry.save()
                    print(
                        'successfully updated individual attendance for %s  of %s'
                        % (student, school))
                except Exception as e:
                    print(
                        'exception 28092019-A from attendance views.py %s %s' %
                        (e.message, type(e)))
                    print('entry does not exist for %s %s. Will create now' %
                          (student, school))
                    entry = IndividualAttendance(student=student)
                    entry.total_days = total_days
                    entry.present_days = present_days
                    entry.absent_days = absent_days
                    entry.save()
                    print(
                        'successfully created individual attendance for %s  of %s'
                        % (student, school))
        context_dict['status'] = 'success'
        return JSONResponse(context_dict, status=200)
示例#12
0
 def delete(self, request, *args, **kwargs):
     context_dict = {}
     id = self.kwargs['id']
     try:
         lecture = Lecture.objects.get(id=id)
         print('deleting lecture title %s subject %s by %s' %
               (lecture.topic, lecture.subject, lecture.teacher))
         lecture.delete()
         message = 'successfully deleted lecture title %s subject %s by %s' % (
             lecture.topic, lecture.subject, lecture.teacher)
         print('message')
     except Exception as e:
         print('exception 06042020-A from lecture views.py %s %s' %
               (e.message, type(e)))
         message = 'Lecture Deletion failed'
     print(message)
     context_dict['message'] = message
     return JSONResponse(context_dict, status=200)
示例#13
0
    def post(self, request, *args, **kwargs):
        answer_sheets = AnswerSheets.objects.all()

        zero_getter_count = 0
        for a_sheet in answer_sheets:
            try:
                online_test = a_sheet.online_test
                exam = online_test.exam
                subject = online_test.subject
                student = a_sheet.student
                the_class = student.current_class
                section = student.current_section

                offline_test = ClassTest.objects.get(exam=exam,
                                                     subject=subject,
                                                     the_class=the_class,
                                                     section=section)
                test_result = TestResults.objects.get(class_test=offline_test,
                                                      student=student)
                marks = test_result.marks_obtained
            except Exception as e:
                print('exception 05052020-E from online_test views.py %s %s' %
                      (e.message, type(e)))
                print('failed to retrieve marks')

            if marks > 0:
                if not a_sheet.shared:
                    link = a_sheet.link
                    message = 'Dear %s, answer sheet of %s online test attached. link:  %s' % \
                              (student, subject, link)
                    print('message: %s' % message)
                    school = a_sheet.student.school
                    mobile = a_sheet.student.parent.parent_mobile1
                    sms.send_sms1(school, '*****@*****.**', mobile, message,
                                  'Share Answer sheet')
                    a_sheet.shared = True
                    a_sheet.save()
            else:
                zero_getter_count += 1
                print(
                    '%s secued zero marks in the online test of %s class %s. hence not sharing'
                    % (student, subject, the_class))
        return JSONResponse({'zero_getter_count': zero_getter_count},
                            status=200)
示例#14
0
    def get(self, request, *args, **kwargs):
        school_id = self.request.query_params.get('school_id')
        school = School.objects.get(id=school_id)
        standard = self.request.query_params.get('the_class')
        the_class = Class.objects.get(school=school, standard=standard)
        sec = request.query_params.get('section')
        section = Section.objects.get(school=school, section=sec)

        try:
            ct = ClassTeacher.objects.get(standard=the_class, section=section)
            class_teacher = '%s %s' % (ct.class_teacher.first_name, ct.class_teacher.last_name)
        except Exception as e:
            print('exception 28022020-A from teachers views.py %s %s' % (e.message, type(e)))
            print('class teacher for %s-%s school %s is not set' % (the_class, section, school))
            class_teacher = 'N/A'
        context_dict = {
            'class_teacher': class_teacher
        }
        return JSONResponse(context_dict, status=200)
示例#15
0
def report_delay(request):
    response = {

        }
    if request.method == 'POST':
        data = json.loads(request.body)
        school_id = data['school_id']
        rout = data['rout']
        teacher = data['teacher']
        message = data['message']

        try:
            school = School.objects.get(id=school_id)
            configuration = Configurations.objects.get(school=school)
            r = Bus_Rout.objects.get(school=school_id, bus_root=rout)
            teacher = Teacher.objects.get(email=teacher)
            email = teacher.email
            student_rout = Student_Rout.objects.filter(bus_root=r)

            school_name = school.school_name
            for sr in student_rout:
                parent = sr.student.parent
                m1 = parent.parent_mobile1
                m2 = parent.parent_mobile2

                full_message = 'Dear ' + parent.parent_name + ', Delay on Bus rout ' + rout
                full_message += ': ' + message + '. Regards, ' + teacher.first_name + ' ' + teacher.last_name
                full_message += ', ' + school_name

                message_type = 'Bus Delay'
                sms.send_sms1(school, email, m1, full_message, message_type)

                if m2 != '':
                    if configuration.send_absence_sms_both_to_parent:
                        sms.send_sms1(school, email, m2, full_message, message_type)

                print (full_message)
        except Exception as e:
            print ('unable to send bus delay message')
            print ('Exception18 in bus_attendance views.py = %s (%s)' % (e.message, type(e)))
    return JSONResponse(response, status=200)
示例#16
0
    def get(self, request, *args, **kwargs):
        attempts = StudentTestAttempt.objects.all()

        failed_attempts = 0
        duplicate_attempts = 0
        for an_attempt in attempts:
            student = an_attempt.student
            online_test = an_attempt.online_test
            try:
                answer_count = StudentQuestion.objects.filter(
                    student=student, question__test=online_test).count()
                if answer_count < 20:
                    print('test date = %s' % str(online_test.date))
                    if str(online_test.date) == '2020-05-04':
                        failed_attempts += 1
                        print(
                            '%s of class %s-%s attempted test %s but only %d answers recorded'
                            % (student, student.current_class,
                               student.current_section, online_test.subject,
                               answer_count))
                if answer_count > 20:
                    if str(online_test.date) == '2020-05-04':
                        duplicate_attempts += 1
                        print(
                            '%s of class %s-%s attempted test %s and %d answers recorded'
                            % (student, student.current_class,
                               student.current_section, online_test.subject,
                               answer_count))

            except Exception as e:
                print('exception 05052020-A from online_test views.py %s %s' %
                      (e.message, type(e)))
                print(
                    'failed to retrieve details of online attempts for %s in %s'
                    % (student, online_test.subject))
        return JSONResponse(
            {
                'failed_attempts': failed_attempts,
                'duplicate_attempts': duplicate_attempts
            },
            status=200)
示例#17
0
def whether_class_teacher2(request, teacher):
    response_dict = {

    }

    if request.method == 'GET':
        try:
            t = Teacher.objects.get(email=teacher)
            response_dict['status'] = 'success'
            if ClassTeacher.objects.filter(class_teacher=t).first():
                ct = ClassTeacher.objects.filter(class_teacher=t)[0]
                response_dict['is_class_teacher'] = 'true'
                response_dict['the_class'] = ct.standard.standard
                response_dict['section'] = ct.section.section
            else:
                response_dict['is_class_teacher'] = 'false'
        except Exception as e:
            print('Exception 70 from teachers views.py %s %s' % (e.message, type(e)))
            response_dict['status'] = 'failure'

    return JSONResponse(response_dict, status=200)
示例#18
0
def process_bus_attendance1(request, att_type, d, m, y, teacher):
    response_data = {

    }
    if request.method == 'POST':
        the_date = date(int(y), int(m), int(d))
        try:
            attendance_type = Attedance_Type.objects.get(route_type=att_type)

        except Exception as e:
            print ('unable to retrieve attendance type for ' + att_type)
            print ('Exception16 in bus_attendance views.py = %s (%s)' % (e.message, type(e)))
        data = json.loads(request.body)
        print ('attendance processing data')
        print (data)
        for key in data:
            student = data[key]
            try:
                st = Student.objects.get(id=student)
                sr = Student_Rout.objects.get(student=st)
                bus_rout = sr.bus_root
                # check whether the attendance for this student for this date has been already marked or not

                q = Bus_Attendance.objects.filter(date=the_date,
                                                  student=st, bus_rout=bus_rout, attendance_type=attendance_type)
                if q.count() == 0:
                    bus_attendance = Bus_Attendance(date=the_date, student=st, bus_rout=bus_rout,
                                                    taken_by=Teacher.objects.get(email=teacher),
                                                    attendance_type=attendance_type)
                    bus_attendance.save()
            except Exception as e:
                print ('unable to save the bus attendance for ' + st.fist_name + ' ' + st.last_name +
                       ' for rout ' + bus_rout.bus_root + ' ' + attendance_type.rout_type
                       + 'on date ' + str(the_date))
                print ('Exception17 in bus_attendance views.py = %s (%s)' % (e.message, type(e)))
                response_data['status'] = 'failure'
            response_data['status'] = 'success'

    return JSONResponse(response_data, status=200)
示例#19
0
    def post(self, request, *args, **kwargs):
        context_dict = {}
        print('request=')
        print(request.body)
        data = json.loads(request.body)
        print('json=')
        print(data)

        for key in data:
            student_id = data[key]['student_id']
            student = Student.objects.get(id=student_id)

            question_id = data[key]['question_id']
            question = OnlineQuestion.objects.get(id=question_id)

            option_marked = data[key]['option_marked']

            student_question = StudentQuestion(student=student,
                                               question=question,
                                               answer_marked=option_marked)
            student_question.save()

        online_test = question.test
        try:
            attempt = StudentTestAttempt.objects.get(student=student,
                                                     online_test=online_test)
            print('%s attempt has already been recorded' % student)
        except Exception as e:
            print('a good exception from online_test views.py %s %s' %
                  (e.message, type(e)))
            print('%s attempt was not recorded' % student)
            attempt = StudentTestAttempt(student=student,
                                         online_test=online_test)
            attempt.save()

        context_dict['status'] = 'success'
        return JSONResponse(context_dict, status=200)
示例#20
0
    def post(self, request, *args, **kwargs):
        context_dict = {}
        print('request=')
        print(request.body)
        data = json.loads(request.body)
        print('json=')
        print(data)
        try:
            student_id = data['student_id']
            student = Student.objects.get(id=student_id)

            question_id = data['question_id']
            question = OnlineQuestion.objects.get(id=question_id)

            answer_marked = data['answer_marked']

            try:
                question = StudentQuestion.objects.get(student=student,
                                                       question=question)
                print('%s has already marked an answer. This will be updated')
                print('changed the answer marked')
            except Exception as e:
                print('exception 17052020-A from online_test views.py %s %s' %
                      (e.message, type(e)))
                print('%s is marking the answer for the first time')
                question = StudentQuestion(student=student, question=question)
                print('changed the answer marked')
            question.answer_marked = answer_marked
            question.save()
            context_dict['status'] = 'success'
        except Exception as e:
            print('exception 17052020-C from online_test views.py %s %s' %
                  (e.message, type(e)))
            print('error decoding json for answer marking')
            context_dict['status'] = 'Fail'
        return JSONResponse(context_dict, status=200)
示例#21
0
def add_teacher(request):
    print('adding teacher from device...')
    response_dict = {

    }
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print(data)
            user = data['user']
            school_id = data['school_id']
            #employee_id = data['employee_id']
            email = data['email']
            mobile = data['mobile']
            full_name = data['full_name']
            first_name = full_name.split()[0]
            last_name = ' '
            try:
                last_name += full_name.split()[1]
                last_name += ' %s' % full_name.split()[2]
            except Exception as e:
                print('exception 03022020-A from teacher views.py %s %s' % (e.message, type(e)))
                print('last name of teacher not mentioned completely')

            school = School.objects.get(id=school_id)

            # check to see if any other teacher in this school has the same login id

            try:
                t = Teacher.objects.get(school=school, email=email)
                response_dict['status'] = 'failed'
                message = 'login id ' + email + ' is already assigned to ' + t.first_name + ' ' + t.last_name
                print(message)
                response_dict['message'] = message
                response_dict['status'] = 'failed'
                return JSONResponse(response_dict, status=201)
            except Exception as e:
                print('Exception 20 from teacher views.py = %s (%s) ' % (e.message, type(e)))
                print('login id are available. Hence this teacher can be added...')
                t = Teacher()
                t.school = school
                t.first_name = first_name
                t.last_name = last_name
                t.email = email
                t.mobile = mobile
                t.active_status = True
                try:
                    t.save()
                    # now, create a user for this teacher
                    # the user name would be the email, and password would be a random string
                    password = User.objects.make_random_password(length=5, allowed_chars='1234567890')

                    print ('Initial password = '******'Successfully created user for ' + first_name + ' ' + last_name)

                        mapping = UserSchoolMapping(user=u, school=school)
                        mapping.save()
                    except Exception as e:
                        print ('Exception 50 from teacher views.py = %s (%s)' % (e.message, type(e)))
                        print ('Unable to create user or user-school mapping for ' + first_name + ' ' + last_name)

                    # make this user part of the Teachers group
                    try:
                        group = Group.objects.get(name='teachers')
                        u.groups.add(group)
                        print ('Successfully added ' + first_name + ' ' + last_name + ' to the Teachers group')
                    except Exception as e:
                        print ('Exception 60 from teacher views.py = %s (%s)' % (e.message, type(e)))
                        print ('Unable to add ' + first_name + ' ' + last_name + ' to the Teachers group')

                    # get the links of app on Google Play and Apple App store
                    configuration = Configurations.objects.get(school=school)
                    android_link = configuration.google_play_link
                    iOS_link = configuration.app_store_link

                    # send login id and password to teacher via sms
                    message = 'Dear ' + first_name + ' ' + last_name + ', Welcome to ClassUp.'
                    message += ' Your user id is: ' + email + ', and password is: ' + password + '. '
                    message += 'Please install ClassUp from these links. Android: '
                    message += android_link
                    message += ', iPhone/iOS: '
                    message += iOS_link

                    message += 'You can change your password after first login. '
                    message += 'Enjoy managing your class with ClassUp!'
                    message += ' For support, email to: [email protected]'
                    message_type = 'Welcome Teacher'
                    sender = user

                    sms.send_sms1(school, sender, str(mobile), message, message_type)

                    # 15/07/2017 - Set up Main as default subject for this teacher
                    try:
                        print ('now trying to set teacher subject')
                        s = Subject.objects.get(school=school, subject_name='Main')
                    except Exception as e:
                        print('unable to retrieve Main subject as default for ')
                        print ('Exception 210 from teachers views.py = %s (%s)' % (e.message, type(e)))

                    try:
                        ts = TeacherSubjects.objects.get(teacher=t, subject=s)
                        if ts:
                            print('subject ' + s.subject_name + ' has already been selected by teacher '
                                  + t.first_name + ' ' + t.last_name)
                            pass

                    except Exception as e:
                        print(
                            'now setting subject ' + s.subject_name + ' for teacher ' +
                            t.first_name + ' ' + t.last_name)
                        ts = TeacherSubjects(teacher=t, subject=s)
                        try:
                            ts.save()
                            print('successfully set subject ' + s.subject_name +
                                  ' for teacher ' + t.first_name + ' ' + t.last_name)
                        except Exception as e:
                            print('unable to set subject ' + s.subject_name +
                                  ' for teacher ' + t.first_name + ' ' + t.last_name)
                            print ('Exception 211 from teachers views.py = %s (%s)' % (e.message, type(e)))

                    response_dict['status'] = 'success'
                    response_dict['message'] = "Teacher created. Welcome SMS sent to the teacher' mobile"
                    return JSONResponse(response_dict, status=200)
                except Exception as e:
                    print('Exception 30 from teacher views.py = %s (%s)' % (e.message, type(e)))
                    message = 'Failed to create Teacher. Please contact ClassUp Support'
                    print(message)
                    response_dict['message'] = message
                    response_dict['status'] = 'failed'
                    return JSONResponse(response_dict, status=201)
        except Exception as e:
            print('Exception 40 from teachers views.py = %s (%s)' % (e.message, type(e)))
            message = 'Failed to create Teacher. Please contact ClassUp Support'
            response_dict['message'] = message
            response_dict['status'] = 'failed'
            print(message)
            return JSONResponse(response_dict, status=201)
示例#22
0
def update_teacher(request):
    response_dict = {

    }
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print(data)
            teacher_id = data['teacher_id']
            teacher_login = data['teacher_login']
            teacher_mobile = data['teacher_mobile']
            teacher_name = data['teacher_name']
            first_name = teacher_name.split()[0]
            last_name = ' '
            try:
                last_name += teacher_name.split()[1]
                last_name += ' %s' % teacher_name.split()[2]
            except Exception as e:
                print('exception 03022020-B from teacher views.py %s %s' % (e.message, type(e)))
                print('last name of teacher not mentioned completely')

            teacher = Teacher.objects.get(id=teacher_id)
            teacher.first_name = first_name
            teacher.last_name = last_name
            teacher.email = teacher_login
            teacher.mobile = teacher_mobile
            teacher.save()

            message = 'Teacher ' + teacher_name + ' updated. '
            print (message)
            response_dict['status'] = 'success'
            response_dict['message'] = message

            if data['is_class_teacher'] == 'true':
                print('starting to set this teacher as Class Teacher...')
                school_id = data['school_id']
                school = School.objects.get(id=school_id)
                the_class = data['the_class']
                c = Class.objects.get(school=school, standard=the_class)
                section = data['section']
                s = Section.objects.get(school=school, section=section)
                t = Teacher.objects.get(id=teacher_id)
                try:
                    ct = ClassTeacher.objects.get(school=school, standard=c, section=s)
                    cct = ct.class_teacher  # current class teacher?
                    ct.class_teacher = t
                    ct.save()
                    message += cct.first_name + ' ' + cct.last_name +  ' was the Class Teacher for class '
                    message += the_class + ' ' + section + '. Now the new Class Teacher is '
                    message += teacher_name
                    print(message)
                    response_dict['message'] = message
                    response_dict['status'] = 'success'
                    return JSONResponse(response_dict, status=200)
                except Exception as e:
                    print('Exception 90 from teachers views.py = %s (%s) ' % (e.message, type(e)))
                    print('no Class Teacher was set for class ' + the_class + ' ' + section + '. Setting now...')
                    try:
                        ct = ClassTeacher()
                        ct.school = school
                        ct.standard = c
                        ct.section = s
                        ct.class_teacher = t
                        ct.save()
                        message += teacher_name + ' is now assigned as Class Teacher for class '
                        message += the_class + ' ' + section
                        print(message)
                        response_dict['message'] = message
                        response_dict['status'] = 'success'
                        return JSONResponse(response_dict, status=200)
                    except Exception as e:
                        print ('Exception 100 from teachers views.py = %s (%s) ' % (e.message, type(e)))
                        error_message = 'failed to set ' + teacher_name + ' as Class Teacher for class: '
                        error_message +=  the_class + ' ' + section
                        print(error_message)
                        response_dict['error_message'] = error_message
                        return JSONResponse(response_dict, status=201)
            return JSONResponse(response_dict, status=200)
        except Exception as e:
            print ('Exception 110 from teachers views.py = %s (%s) ' % (e.message, type(e)))
            error_message = 'Failed to update teacher'
            print(error_message)
            response_dict['status'] = 'failure'
            response_dict['error_message'] = error_message
            return JSONResponse(response_dict, status=201)
示例#23
0
def retrieve_stu_att_summary(request):
    dict_attendance_summary = {

    }
    response_array = []

    if request.method == 'GET':
        student_id = request.GET.get('student_id')
    student = Student.objects.get(id=student_id)
    school = student.school
    c = Configurations.objects.get(school=school)
    session_start_month = c.session_start_month
    print (session_start_month)

    the_class = student.current_class
    section = student.current_section

    # 22/08/2016 logic - Coaching classes and Colleges prefer to conduct attendance subject wise and hence
    # Main subject may not exist for them. In this case we will be presenting the aggregate of attendance for all
    # the subjects. This will be done by first checking the existence of subject Main. If it is present the
    # calculations are based on attendance in Main subjects, else aggregate of all subjects
    main_exist = True
    try:
        main = Subject.objects.get(school=school, subject_name='Main')
    except Exception as e:
        print ('Main subject does not exist for this school/Coaching Institute')
        print ('Exception4 from parents views.py = %s (%s)' % (e.message, type(e)))
        main_exist = False

    now = datetime.datetime.now()
    work_days = 0
    if now.month < session_start_month:
        print ('current month is less than session start month. Hence starting from last year')
        for m in range(session_start_month, 12 + 1):  # 12+1, because loop executes for 1 time less than max index
            month_year = calendar.month_abbr[m] + '/' + str(now.year - 1)
            dict_attendance_summary["month_year"] = month_year
            try:
                if main_exist:
                    query = AttendanceTaken.objects.filter(date__month=m, date__year=now.year - 1, subject=main,
                                                           the_class=the_class, section=section)
                else:
                    query = AttendanceTaken.objects.filter(date__month=m, date__year=now.year - 1,
                                                           the_class=the_class, section=section)
                work_days = query.count()
                dict_attendance_summary["work_days"] = work_days
                print ('days in ' + str(m) + '/' + str(now.year - 1) + '=' + str(work_days))
            except Exception as e:
                print ('unable to fetch the number of days for ' + month_year)
                print ('Exception5 from parents views.py = %s (%s)' % (e.message, type(e)))
            try:
                if main_exist:
                    query = Attendance.objects.filter(student=student, subject=main,
                                                      date__month=m, date__year=now.year - 1)
                else:
                    query = Attendance.objects.filter(student=student, date__month=m, date__year=now.year - 1)
                absent_days = query.count()
                dict_attendance_summary["absent_days"] = absent_days
                present_days = work_days - absent_days
                dict_attendance_summary["present_days"] = present_days

                if work_days != 0:
                    present_perc = round((float(present_days) / float(work_days)) * 100, 2)
                    dict_attendance_summary['percentage'] = str(present_perc) + '%'
                else:
                    dict_attendance_summary['percentage'] = 'N/A'
                print ('absent days for ' + str(m) + '/' + str(now.year - 1) + '=' + str(query.count()))
            except Exception as e:
                print ('unable to fetch absent days for ' + str(m) + '/' + str(now.year - 1))
                print ('Exception6 from parents views.py = %s (%s)' % (e.message, type(e)))
            d = dict(dict_attendance_summary)
            response_array.append(d)
        for m in range(1, now.month + 1):
            month_year = calendar.month_abbr[m] + '/' + str(now.year)
            dict_attendance_summary["month_year"] = month_year
            try:
                if main_exist:
                    query = AttendanceTaken.objects.filter(date__month=m, date__year=now.year,
                                                           subject=main, the_class=the_class, section=section)
                else:
                    query = AttendanceTaken.objects.filter(date__month=m, date__year=now.year,
                                                           the_class=the_class, section=section)
                work_days = query.count()
                dict_attendance_summary["work_days"] = work_days
                print ('days in ' + str(m) + '/' + str(now.year) + '=' + str(work_days))
            except Exception as e:
                print ('unable to fetch the number of days for ' + str(m) + '/' + str(now.year))
                print ('Exception7 from parents views.py = %s (%s)' % (e.message, type(e)))
            try:
                if main_exist:
                    query = Attendance.objects.filter(student=student, subject=main,
                                                      date__month=m, date__year=now.year)
                else:
                    query = Attendance.objects.filter(student=student, date__month=m, date__year=now.year)
                absent_days = query.count()
                dict_attendance_summary["absent_days"] = absent_days
                present_days = work_days - absent_days
                dict_attendance_summary["present_days"] = present_days
                if work_days != 0:
                    present_perc = round((float(present_days) / float(work_days)) * 100, 2)
                    dict_attendance_summary['percentage'] = str(present_perc) + '%'
                else:
                    dict_attendance_summary['percentage'] = 'N/A'
                print ('absent days for ' + str(m) + '/' + str(now.year) + '=' + str(query.count()))
            except Exception as e:
                print ('unable to fetch absent days for ' + str(m) + '/' + str(now.year))
                print ('Exception8 from parents views.py = %s (%s)' % (e.message, type(e)))
            d = dict(dict_attendance_summary)
            response_array.append(d)

    # if current month is higher than the session_start_month then we need to add the working days
    # session start month till current-1 month
    else:
        for m in range(session_start_month, now.month + 1):
            month_year = calendar.month_abbr[m] + '/' + str(now.year)
            dict_attendance_summary["month_year"] = month_year
            try:
                if main_exist:
                    query = AttendanceTaken.objects.filter(date__month=m, date__year=now.year,
                                                           subject=main, the_class=the_class, section=section)
                else:
                    query = AttendanceTaken.objects.filter(date__month=m, date__year=now.year,
                                                           the_class=the_class, section=section)
                work_days = query.count()
                dict_attendance_summary["work_days"] = work_days
                print ('days in ' + str(m) + '/' + str(now.year) + '=' + str(work_days))
            except Exception as e:
                print ('unable to fetch the number of days for ' + str(m) + '/' + str(now.year))
                print ('Exception9 from parents views.py = %s (%s)' % (e.message, type(e)))
            try:
                if main_exist:
                    query = Attendance.objects.filter(student=student, subject=main,
                                                      date__month=m, date__year=now.year)
                else:
                    query = Attendance.objects.filter(student=student, date__month=m, date__year=now.year)
                absent_days = query.count()
                dict_attendance_summary["absent_days"] = absent_days
                present_days = work_days - absent_days
                dict_attendance_summary["present_days"] = present_days
                if work_days != 0:
                    present_perc = round((float(present_days) / float(work_days)) * 100, 2)
                    dict_attendance_summary['percentage'] = str(present_perc) + '%'
                else:
                    dict_attendance_summary['percentage'] = 'N/A'

                print ('absent days for ' + str(m) + '/' + str(now.year) + '=' + str(query.count()))

            except Exception as e:
                print ('unable to fetch absent days for ' + str(m) + '/' + str(now.year))
                print ('Exception10 from parents views.py = %s (%s)' % (e.message, type(e)))
            d = dict(dict_attendance_summary)

            response_array.append(d)
    print (response_array.__len__())

    try:
        parent_mobile = student.parent.parent_mobile1
        action = 'Retrieved ' + student.fist_name + ' ' + student.last_name + ' Attendance History'
        log_entry(parent_mobile, action, 'Normal', True)
    except Exception as e:
        print('unable to create logbook entry')
        print ('Exception 505 from parents views.py %s %s' % (e.message, type(e)))

    return JSONResponse(response_array, status=200)
示例#24
0
    def post(self, request, *args, **kwargs):
        message_type = 'Share Lecture'
        context_dict = {'message_type': message_type}
        print(request.POST)
        school_id = request.POST.get('school_id')
        print('school_id = %s' % school_id)
        school = School.objects.get(id=school_id)
        print('school = %s' % school)
        teacher_email = request.POST.get('teacher')
        teacher = Teacher.objects.get(email=teacher_email)
        print('teacher = %s' % teacher)
        print('school = %s' % school)
        standard = request.POST.get('the_class')
        the_class = Class.objects.get(school=school, standard=standard)
        print('the_class = %s' % the_class)

        sec = request.POST.get('section')
        print('sec = %s' % sec)
        if sec != '':
            section = sec.split(',')
            # section = Section.objects.get(school=school, section=sec)
            print('section = %s' % section)
        all_sections = request.POST.get('all_sections')
        print(all_sections)

        sub = request.POST.get('subject')
        subject = Subject.objects.get(school=school, subject_name=sub)
        print('subject = %s' % subject)
        youtube_link = request.POST.get('youtube_link')
        print('youtube_link = %s' % youtube_link)
        if youtube_link == '':
            youtube_link = 'N/A'
        lesson_topic = request.POST.get('lesson_topic')
        print('lesson_topic = %s' % lesson_topic)
        try:
            lecture = Lecture(teacher=teacher,
                              the_class=the_class,
                              subject=subject,
                              topic=lesson_topic,
                              youtube_link=youtube_link)
            lecture.save()
        except Exception as e:
            print('exception 29032020-A from lecture views.py %s %s' %
                  (e.message, type(e)))
            print('failed in creating lecture record')

        file_included = request.POST.get('file_included')
        print('file_included = %s' % file_included)

        if file_included == 'true' or file_included == 'yes':
            include_link = True
            doc_file = request.FILES['file']
            print(type(doc_file))
            print('doc_file = %s' % doc_file)
            print(doc_file)

            # 05/04/2020 - a lot of stupid teachers use characters like (, ), & in file name which causes issues
            file_name3 = request.POST.get('file_name').replace(' ', '_')
            file_name2 = file_name3.replace('&', '_')
            file_name1 = file_name2.replace('(', '_')
            file_name = file_name1.replace(')', '_')
            # long_link = 'https://storage.cloud.google.com/classup/classup2/media/prod/image_video/%s' % \
            #             image_name.replace('@', '')
            long_link = 'https://classup2.s3.us-east-2.amazonaws.com/media/prod/image_video/%s' % \
                        file_name.replace('@', '')
            print('long_link = %s' % long_link)
            short_link = long_link

            # prepare short link
            global_conf = GlobalConf.objects.get(pk=1)
            key = global_conf.short_link_api
            url = 'https://cutt.ly/api/api.php?'
            url += 'key=%s&short=%s' % (key, long_link)
            print('url for generating short link = %s' % url)
            try:
                req = urllib2.Request(url,
                                      headers={'User-Agent': "Magic Browser"})
                response = urllib2.urlopen(req)
                print('response for generating short link = %s' % response)
                outcome = json.loads(response.read())
                print('ouctome = ')
                print(outcome)
                status = outcome['url']['status']
                print('status = %i' % status)
                if status == 7:
                    short_link = outcome['url']['shortLink']
                    print('short_lint = %s' % short_link)
            except Exception as e:
                print('exception 14122019-B-A from lecture views.py %s %s' %
                      (e.message, type(e)))
                print(
                    'failed to generate short link  for the lesson doc uploaded by %s'
                    % teacher)

            try:
                print('doc_file = ')
                print(doc_file)
                lecture.pdf_link = short_link
                lecture.doc_file = doc_file
                lecture.save()
            except Exception as e:
                print('exception 29032020-B from lecture views.py %s %s' %
                      (e.message, type(e)))
                print('error in saving document pdf')

        if all_sections == 'true' or all_sections == 'yes':
            print('this lecture to be shared with all sections of class %s' %
                  the_class)
            students = Student.objects.filter(current_class=the_class,
                                              active_status=True)
        else:
            print('this lecture to be shared with class %s-%s' %
                  (the_class, section))
            sections = reduce(lambda x, y: x | y, [
                Q(current_section=Section.objects.get(school=school,
                                                      section=a_section))
                for a_section in section
            ])
            print(sections)
            try:
                students = Student.objects.filter(sections,
                                                  current_class=the_class,
                                                  active_status=True)
                print(students)
            except Exception as e:
                print('exception 07042020-A from lecture views.py %s %s' %
                      (e.message, type(e)))

        for student in students:
            message = 'Dear %s, class %s %s %s lecture shared. Link:  %s ' % \
                      (student, standard, sub, lesson_topic, youtube_link)
            if file_included == 'true' or file_included == 'yes':
                message += '  Assignment link: %s' % short_link
            print(message)
            p = student.parent
            m1 = p.parent_mobile1
            sms.send_sms1(school, teacher_email, m1, message, message_type)
        return JSONResponse(context_dict, status=200)
示例#25
0
    def post(self, request, *args, **kwargs):
        print('user id in post request = ')
        data = request.POST
        print(data)
        context_dict = {}
        try:
            storage = DjangoORMStorage(CredentialModel, 'id', 1, 'credential')

            credential = storage.get()
            print('credential = ')
            print(credential)
            if credential is None or credential.invalid == True:
                print('credential found to be invalid or None')
            else:
                print('credentials are found to be valid')

            client = build('youtube',
                           'v3',
                           http=credential.authorize(httplib2.Http()))
            print('client = ')
            print(client)

            params = (request.POST['params'])
            print(params)
            data = json.loads(params)
            print('Video sharing process started')
            teacher = data['teacher']
            t = Teacher.objects.get(email=teacher)
            print(t)
            print(teacher)
            the_class = data['the_class']
            print(the_class)
            c = Class.objects.get(school=t.school, standard=the_class)
            print(c)
            section = data['section']
            print(section)
            s = Section.objects.get(school=t.school, section=section)
            print(s)
            description = data['description']
            whole_class = data['whole_class']
            print('whole class = %s' % whole_class)
            if whole_class == 'false':
                student_list = data['student_list']
                print(student_list)
                print(type(student_list))

                # 29/08/2019 - when comes from Android, the student id list comes as an array. So we need to break it
                # into list. But from iOS, it comes as a proper list. So need not break it
                try:
                    students = ast.literal_eval(student_list)
                    print(students)
                except Exception as e:
                    print(
                        'exception 04092019-A from pic_share views.py %s %s' %
                        (e.message, type(e)))
                    print(
                        'looks the request has come from iOS, hence no need for ast.literal_eval'
                    )
                    students = student_list
            print(
                'will now save the video received in local storage temporarily'
            )
            print(request.FILES)
            up_file = request.FILES['video']
            folder = 'uploaded_videos'
            fs = FileSystemStorage(location=folder)  # defaults to   MEDIA_ROOT
            filename = fs.save(up_file.name, up_file)
            print('file successfully saved locally %s' % filename)

            body = dict(snippet=dict(title=description,
                                     description=description,
                                     tags=['ClassUp'],
                                     categoryId=22),
                        status=dict(privacyStatus='private'))
            file_location = '%s/%s' % (folder, filename)
            insert_request = client.videos().insert(
                part=','.join(body.keys()),
                body=body,
                media_body=MediaFileUpload(
                    file_location,
                    #chunksize=-1,
                    chunksize=5 * 1024 * 1024,
                    resumable=True))
            status, video_id = resumable_upload(insert_request)
            if status == 'success':
                link = ''
        except Exception as e:
            print('exception 02092019-A from pic_share views.py %s %s' %
                  (e.message, type(e)))
            print('failed to upload to YouTube')

        return JSONResponse(context_dict, status=200)
示例#26
0
    def post(self, request, *args, **kwargs):
        # connect to AWS s3 bucket and
        try:
            session = boto3.Session(
                aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
                aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
            )
            s3 = session.resource('s3')
            print('s3 session established successfully')
        except Exception as e:
            print('exception 05052020-C from online_test views.py %s %s' %
                  (e.message, type(e)))
            print('failed estable connections to AWS S3 storage')

        attempts = StudentTestAttempt.objects.all()
        # attempts = StudentTestAttempt.objects.filter(student__fist_name='Devrat',
        #                                              online_test__subject__subject_name='English')
        print(attempts)

        for an_attempt in attempts:
            marks_obtained = 0
            student = an_attempt.student
            online_test = an_attempt.online_test
            questions = OnlineQuestion.objects.filter(test=online_test)
            for a_question in questions:
                try:
                    student_answer = StudentQuestion.objects.get(
                        student=student, question=a_question)
                    option_marked = student_answer.answer_marked
                    correct_option = a_question.correct_option

                    if option_marked.strip() == correct_option.strip():
                        marks_obtained += 1
                except Exception as e:
                    print(
                        'exception 29042020-X from online_test views.py %s %s'
                        % (e.message, type(e)))
                    print(
                        'could not retrieve student %s attempt for question' %
                        (student))
                    an_attempt.submission_ok = False
                    an_attempt.save()
                    continue

            # update marks in corresponding offline test_date
            try:
                offline_test = ClassTest.objects.get(
                    exam=online_test.exam,
                    subject=online_test.subject,
                    the_class=online_test.the_class,
                    section=student.current_section)
                offline_result = TestResults.objects.get(
                    student=student, class_test=offline_test)
                offline_result.marks_obtained = marks_obtained
                offline_result.save()
                print(
                    'successfully saved offline test marks for %s in %s class %s exam %s'
                    % (student, student.current_class, online_test.subject,
                       online_test.exam))
            except Exception as e:
                print('exception 30042020-B from online_test view.py %s %s' %
                      (e.message, type(e)))
                print(
                    'failed to fill offline test marks for %s in %s class %s exam %s'
                    % (student, student.current_class, online_test.subject,
                       online_test.exam))

            try:
                answer_sheet = AnswerSheets.objects.get(
                    student=student, online_test=online_test)
                print(
                    'answer sheet for %s for online test %s class %s has already been generated. Skipping'
                    % (student, online_test.subject, online_test.the_class))
                continue
            except Exception as e:
                print(
                    'answer sheet for %s for online test %s class %s has not been generated. Will do now'
                    % (student, online_test.subject, online_test.the_class))
            print(
                'generating result for %s in online test class %s subject %s' %
                (student, online_test.the_class, online_test.subject))

            pdf_name = 'online_test/%s_%s_answer_sheet_online_test_%s_class_%s.pdf' % \
                       (student.fist_name, str(student.id), student.current_class, online_test.subject)
            print('pdf_name = %s' % pdf_name)
            response = HttpResponse(content_type='application/pdf')
            content_disposition = ('attachment; filename= %s' % pdf_name)
            print(content_disposition)
            response['Content-Disposition'] = content_disposition
            print(response)
            c = canvas.Canvas(pdf_name, pagesize=A4, bottomup=1)

            font = 'Times-Bold'
            c.setFont(font, 12)
            font = 'Times-Bold'
            top = 750
            school = student.school
            ms = Marksheet.objects.get(school=school)
            title_start = ms.title_start
            c.drawString(title_start + 80, top, school.school_name)
            c.setFont(font, 8)
            top -= 10
            c.drawString(title_start + 100, top, 'Online Test Sheet')
            top -= 20
            c.drawString(60, top, 'Name: %s' % student)
            c.drawString(175, top, 'Class: %s' % student.current_class)
            c.drawString(
                260, top,
                'Subject: %s (%s)' % (online_test.subject, online_test.exam))

            print('number of questions in this test: %d' % questions.count())
            c.drawString(400, top,
                         'Marks Obtained: %s / 20' % str(marks_obtained))

            top -= 20
            left = 100
            tick_mark = Image.open('online_test/correct.png')
            cross = Image.open('online_test/cross.png')

            print('number of questions in this test: %d' % questions.count())
            q_no = 1
            for a_question in questions:
                if q_no == 9 or q_no == 17:
                    top = 750
                    c.showPage()
                    c.setFont(font, 8)

                c.drawString(left, top,
                             'Q %s - %s' % (str(q_no), a_question.question))
                top -= 15
                c.drawString(left, top, 'A.   %s' % a_question.option_a)
                top -= 10
                c.drawString(left, top, 'B.   %s' % a_question.option_b)
                top -= 10
                c.drawString(left, top, 'C.   %s' % a_question.option_c)
                top -= 10
                c.drawString(left, top, 'D.   %s' % a_question.option_d)
                top -= 15
                c.drawString(left, top,
                             'Correct Option:  %s' % a_question.correct_option)
                try:
                    student_answer = StudentQuestion.objects.get(
                        student=student, question=a_question)
                    option_marked = student_answer.answer_marked
                    correct_option = a_question.correct_option
                    print(
                        'for question %d, %s has marked %s and correct option is %s'
                        % (q_no, student, student_answer.answer_marked,
                           a_question.correct_option))
                    c.drawString(
                        left + 100, top,
                        'Your Answer: %s' % student_answer.answer_marked)

                    if option_marked.strip() == correct_option.strip():
                        print('%s has marked question: %d correct.' %
                              (student, q_no))
                        c.drawInlineImage(tick_mark,
                                          left - 30,
                                          top + 20,
                                          width=15,
                                          height=15)
                        c.drawString(left + 220, top, 'Marks: 1')
                    else:
                        print('%s has marked question: %d wrong.' %
                              (student, q_no))
                        c.drawInlineImage(cross,
                                          left - 30,
                                          top + 20,
                                          width=15,
                                          height=15)
                        c.drawString(left + 220, top, 'Marks: 0')
                except Exception as e:
                    print(
                        'exception 29042020-A from online_test views.py %s %s'
                        % (e.message, type(e)))
                    print(
                        'could not retrieve student %s attempt for question' %
                        (student))

                top -= 20
                q_no += 1

            context_dict = {'marks_obtained': marks_obtained}
            c.save()

            print('uploading %s online test %s class %s to AWS S3 Storage' %
                  (student, online_test.subject, online_test.the_class))
            try:
                s3.meta.client.upload_file(Filename=pdf_name,
                                           Bucket='classup2',
                                           Key='classup2/%s' % pdf_name)
                print('uploaded')
            except Exception as e:
                print('exception 05052020-B from online_test views.py %s %s' %
                      (e.message, type(e)))
                print(
                    'failed to upload answer sheet for %s to AWS S3 storage' %
                    student)

            print('will now try to generate short link')
            long_link = 'https://classup2.s3.us-east-2.amazonaws.com/classup2/%s' % pdf_name
            print('long link: %s' % long_link)
            # prepare short link
            global_conf = GlobalConf.objects.get(pk=1)
            key = global_conf.short_link_api
            url = 'https://cutt.ly/api/api.php?'
            url += 'key=%s&short=%s' % (key, long_link)
            print('url for generating short link = %s' % url)
            try:
                req = urllib2.Request(url,
                                      headers={'User-Agent': "Magic Browser"})
                response = urllib2.urlopen(req)
                print('response for generating short link = %s' % response)
                outcome = json.loads(response.read())
                print('ouctome = ')
                print(outcome)
                status = outcome['url']['status']
                print('status = %i' % status)
                if status == 7:
                    short_link = outcome['url']['shortLink']
                    print('short_lint = %s' % short_link)
            except Exception as e:
                print('exception 30042020-A from online_test views.py %s %s' %
                      (e.message, type(e)))
                print(
                    'failed to generate short link  for the lesson doc uploaded by %s'
                )
                short_link = long_link

            try:
                answer_sheet = AnswerSheets.objects.get(
                    student=student, online_test=online_test)
                print(
                    'answer sheet for %s of class %s-%s in for the online test of %s exists. Now updated'
                    % (student, student.current_class, student.current_section,
                       online_test.subject))
                answer_sheet.link = short_link
            except Exception as e:
                print('exception 05052020-A from online_test views.py %s %s' %
                      (e.message, type(e)))
                print(
                    'answer sheet for %s of class %s-%s in for the online test of %s creating for the first time.'
                    % (student, student.current_class, student.current_section,
                       online_test.subject))
                answer_sheet = AnswerSheets(student=student,
                                            online_test=online_test)
                answer_sheet.link = short_link
            answer_sheet.save()
            os.remove(pdf_name)
            # return response

        return JSONResponse(context_dict, status=200)
示例#27
0
def get_exam_result(request, student_id, exam_id):
    exam_result = {

    }
    response_array = []

    higher_classes = ['XI', 'XII']
    ninth_tenth = ['IX', 'X']
    middle_classes = ['V', 'VI', 'VII', 'VIII']

    prac_subjects = ["Biology", "Physics", "Chemistry",
                     "Accountancy", "Business Studies", "Economics", "Fine Arts",
                     "Information Practices", "Informatics Practices", "Computer Science", "Painting",
                     "Physical Education"]

    if request.method == 'GET':
        student = Student.objects.get(id=student_id)
        student_name = '%s %s' % (student.fist_name, student.last_name)
        print (student_name)
        the_class = student.current_class.standard
        print('%s is in class %s' % (student_name, the_class))
        exam = Exam.objects.get(id=exam_id)
        print (exam)

        start_date = exam.start_date
        end_date = exam.end_date

        # get the list of tests conducted for the class/section of the student between the exam start and end dates
        try:
            test_list = ClassTest.objects.filter(date_conducted__gte=start_date, date_conducted__lte=end_date,
                                                 the_class=student.current_class, section=student.current_section)
            print (test_list)
            for test in test_list:
                print (test)
                exam_result['subject'] = test.subject.subject_name
                print (exam_result)

                # 27/03/2018 - in case of third language in V-VIII, second language in IX and all subjects in XI
                # the student may have not opted for it. So a check has to be made
                try:
                    tr = TestResults.objects.get(class_test=test, student=student)
                    print (tr)
                    if test.grade_based:
                        exam_result['max_marks'] = 'Grade Based'
                        exam_result['marks'] = tr.grade
                        exam_result['average'] = 'N/A'
                        exam_result['highest'] = 'N/A'
                    else:
                        if test.test_type == 'term':
                            print('this is a term test')
                            exam_result['max_marks'] = 100
                            main = tr.marks_obtained
                            # if student was absent then main marks would be -1000
                            if float(main) < 0.0:
                                print('%s was absent in the test of %s' % (student_name, test.subject.subject_name))
                                main = 0.0
                            print('this is a term test. PA, Notebook Sub & Sub Enrich marks/prac will be considered')
                            ttr = TermTestResult.objects.get(test_result=tr)
                            if the_class in higher_classes:
                                prac = 0.0
                                if test.subject.subject_name in prac_subjects:
                                    prac = ttr.prac_marks
                                total = float(main) + float(prac)
                                exam_result['marks'] = total
                            else:
                                pa = ttr.periodic_test_marks
                                notebook = ttr.note_book_marks
                                sub_enrich = ttr.sub_enrich_marks
                                multi_asses = ttr.multi_asses_marks
                                total = float(main) + float(pa) + float(notebook) + float(sub_enrich) + float(
                                    multi_asses)
                                exam_result['marks'] = round(total, 2)
                        else:
                            print('this is a unit test')
                            exam_result['max_marks'] = test.max_marks
                            marks_obtained = tr.marks_obtained
                            print (marks_obtained)
                            if marks_obtained == -5000.00:
                                marks_obtained = ' '
                            exam_result['marks'] = marks_obtained
                            highest = TestResults.objects.filter(class_test=test).aggregate(Max('marks_obtained'))
                            exam_result['highest'] = highest['marks_obtained__max']

                            total = TestResults.objects.filter(class_test=test,
                                                               marks_obtained__gt=0).aggregate(Sum('marks_obtained'))
                            appeared = TestResults.objects.filter(class_test=test, marks_obtained__gt=0).count()
                            exam_result['appeared'] = appeared
                            exam_result['average'] = '%.2f' % float(total['marks_obtained__sum']/appeared)

                    d = dict(exam_result)
                    response_array.append(d)
                except Exception as e:
                    print('exception 27032018-A from parents views.py %s %s' % (e.message, type(e)))
                    print('subject %s is not opted by %s' % (test.subject.subject_name, student_name))
            return JSONResponse(response_array, status=200)
        except Exception as e:
            print (exam_result)
            print ('Exception 13 from parents views.py = %s (%s)' % (e.message, type(e)))
            print ('unable to retrieve ' + exam.title + ' results for ' +
                   student.fist_name + ' ' + student.last_name)
    return JSONResponse(response_array, status=201)
示例#28
0
    def post(self, request, *args, **kwargs):
        print('resuest = ')
        print(request.FILES)
        context_dict = {}
        school_id = self.kwargs['school_id']
        school = School.objects.get(pk=school_id)
        print('school = %s' % school)

        try:
            print(
                'now starting to process the uploaded file for fee upload...')
            fileToProcess_handle = request.FILES['online_test.xlsx']
            print(fileToProcess_handle)
            fileToProcess = xlrd.open_workbook(
                filename=None,
                file_contents=fileToProcess_handle.read(),
                encoding_override="cp1252")
            sheet = fileToProcess.sheet_by_index(0)
            if sheet:
                print('Successfully got hold of sheet!')
            row = 0
            for row1 in range(sheet.nrows):
                if row == 142:
                    break
                print('at the top of the loop, row = %i' % row)
                col = 1
                if row == 1:
                    print('A - row = %i' % row)
                    row += 1
                    continue
                if row == 0:
                    print('B - row = %i' % row)
                    standard = sheet.cell(row, col).value
                    print('standard = %s' % standard)
                    the_class = Class.objects.get(school=school,
                                                  standard=standard)

                    col += 2
                    sub_name = sheet.cell(row, col).value
                    subject = Subject.objects.get(school=school,
                                                  subject_name=sub_name)

                    col += 4
                    teacher_id = sheet.cell(row, col).value
                    print('teacher_id = %s' % teacher_id)
                    teacher = Teacher.objects.get(email=teacher_id)

                    col += 1
                    date = sheet.cell(row, col).value
                    try:
                        test_date = dt.datetime(*xlrd.xldate_as_tuple(
                            date, fileToProcess.datemode))
                        print('test date is in acceptable format')
                        print(test_date)
                    except Exception as e:
                        print('problem with date')
                        print(
                            'exception 18042020-H from online_test views.py %s %s '
                            % (e.message, type(e)))
                        continue

                    col += 1
                    exam_title = sheet.cell(row, col).value
                    print('exam_title = %s' % exam_title)
                    try:
                        exam = Exam.objects.get(school=school,
                                                title=exam_title)
                        print('exam fetched %s' % exam)
                    except Exception as e:
                        print(
                            'exception 01052020-A from online_test views.py %s %s'
                            % (e.message, type(e)))

                    # create online test
                    try:
                        test = OnlineTest.objects.get(school=school,
                                                      the_class=the_class,
                                                      subject=subject,
                                                      exam=exam)
                        print(
                            'online test for class %s subject %s exam %s has already been created'
                            % (the_class, subject, exam))
                        return JSONResponse(context_dict, status=200)
                    except Exception as e:
                        print(
                            'exception 28042020-A from online_test views.py %s %s'
                            % (e.message, type(e)))
                        print(
                            'online test for class %s subject %s exam %s has not been created'
                            % (the_class, subject, exam))
                        online_test = OnlineTest(school=school,
                                                 the_class=the_class,
                                                 subject=subject,
                                                 teacher=teacher,
                                                 date=test_date,
                                                 exam=exam)
                        online_test.save()
                        row += 1
                if row > 1:
                    print('C - row = %i' % row)
                    col = 1
                    try:
                        question = sheet.cell(row, col).value
                        row += 1
                        option_a = sheet.cell(row, col).value
                        row += 1
                        option_b = sheet.cell(row, col).value
                        row += 1
                        option_c = sheet.cell(row, col).value
                        row += 1
                        option_d = sheet.cell(row, col).value
                        row += 1
                        correct_option = sheet.cell(row, col).value
                    except Exception as e:
                        print(
                            'exception 01052020-X from online_test viws.py %s %s'
                            % (e.message, type(e)))

                    online_question = OnlineQuestion(
                        test=online_test,
                        question=question,
                        option_a=option_a,
                        option_b=option_b,
                        option_c=option_c,
                        option_d=option_d,
                        correct_option=correct_option)
                    online_question.save()
                    row += 2
                    print('D - row = %i' % row)
        except Exception as e:
            print('exception 17042020-A from online_test views.py %s %s' %
                  (e.message, type(e)))
            print('failed to create online test')

        # now create a manual test
        wings = get_wings(school)
        ninth_tenth = wings['ninth_tenth']
        higher_classes = wings['higher_classes']
        sections = Section.objects.filter(school=school)
        for section in sections:
            students = Student.objects.filter(current_class=the_class,
                                              current_section=section,
                                              active_status=True)
            if students.count() > 0:
                # check if this test has already been created by some other teacher
                q = ClassTest.objects.filter(exam=exam,
                                             the_class=the_class,
                                             section=section,
                                             subject=subject)
                if q.count() > 0:
                    teacher = q[:1].get().teacher
                    name = '%s %s' % (teacher.first_name, teacher.last_name)
                    outcome = (
                        'test for %s %s %s-%s already created by %s. Hence not creating'
                        % (exam, subject, the_class, section, name))
                    print(outcome)
                    continue

                print('test for %s %s %s-%s does not exist. Hence  creating' %
                      (exam, subject, the_class, section))
                try:
                    print(test_date)
                    print(teacher)
                    test = ClassTest(date_conducted=test_date,
                                     exam=exam,
                                     the_class=the_class,
                                     section=section,
                                     subject=subject,
                                     teacher=teacher,
                                     grade_based=False)
                    test.max_marks = float(
                        20.00
                    )  # max_marks and pass_marks are passed as strings
                    test.passing_marks = float(8.00)
                    test.save()
                    print(
                        'successfully scheduled test for %s class %s-%s for %s'
                        % (subject, the_class, section, exam))
                except Exception as e:
                    print(
                        'exception 28042020-B from online_test views.py %s %s'
                        % (e.message, type(e)))
                    outcome = 'failed to create test for %s class %s-%s for %s' % (
                        subject, the_class, section, exam)
                    print(outcome)
                    continue
                for student in students:
                    # for higher classes (XI & XII) we need to look into the student subject mapping
                    if the_class.standard in higher_classes:
                        print(
                            'test is for higher class %s. Hence, mapping will be considered'
                            % the_class)
                        try:
                            mapping = HigherClassMapping.objects.get(
                                student=student, subject=subject)
                            if mapping:
                                test_result = TestResults(
                                    class_test=test,
                                    roll_no=student.roll_number,
                                    student=student,
                                    marks_obtained=-5000.00,
                                    grade='')
                                test_result.save()
                                print(
                                    'test results successfully created for %s'
                                    % (student))
                        except Exception as e:
                            print(
                                'mapping does not exist between subject %s and %s'
                                % (subject, student))
                            print(
                                'exception 28042020-C from exam online_test view.py %s %s'
                                % (e.message, type(e)))
                    else:
                        # 06/11/2017 if the subject is third language or elective subject (class XI & XII),
                        #  we need to filter students
                        if (subject.subject_type == 'Third Language') or \
                                ((the_class in ninth_tenth) and (subject.subject_name == 'Hindi')):
                            print(
                                'this is a second/third language. Hence test results will be created for selected students'
                            )
                            try:
                                third_lang = ThirdLang.objects.get(
                                    third_lang=subject, student=student)
                                print(
                                    '%s has chosen %s as second/third language'
                                    % (student.fist_name, subject))
                                test_result = TestResults(
                                    class_test=test,
                                    roll_no=student.roll_number,
                                    student=third_lang.student,
                                    marks_obtained=-5000.00,
                                    grade='')
                                try:
                                    test_result.save()
                                    print(
                                        'test results successfully created for %s'
                                        % student)
                                except Exception as e:
                                    print(
                                        'failed to create test results for %s'
                                        % student)
                                    print(
                                        'Exception 28042020-D from online_test views.py = %s (%s)'
                                        % (e.message, type(e)))
                                    context_dict[
                                        'outcome'] = 'Failed to create test'
                                    return JSONResponse(context_dict,
                                                        status=201)
                            except Exception as e:
                                print(
                                    'Exception 20112019-E from exam test_management.py %s %s'
                                    % (e.message, type(e)))
                                print(
                                    '%s has not chosen %s as third language' %
                                    (student, subject))
                        else:
                            print(
                                'this is a regular subject. Hence test results will be created for all students'
                            )
                            test_result = TestResults(
                                class_test=test,
                                roll_no=student.roll_number,
                                student=student,
                                marks_obtained=-5000.00,
                                grade='')
                            try:
                                test_result.save()
                                print(
                                    'test results successfully created for %s'
                                    % student)
                            except Exception as e:
                                print('failed to create test results for %s' %
                                      student)
                                print(
                                    'Exception 28042020-F from online_test views.py %s %s'
                                    % (e.message, type(e)))
                                context_dict[
                                    'outcome'] = 'Failed to create test'
                                return JSONResponse(context_dict, status=201)
        return JSONResponse(context_dict, status=200)
示例#29
0
    def post(self, request, *args, **kwargs):
        context_dict = {}
        context_dict['header'] = 'Share Image'
        try:
            data = json.loads(request.body)
            print('Image sharing process started')
            teacher = data['teacher']
            t = Teacher.objects.get(email=teacher)
            print(t)
            print(teacher)
            the_class = data['class']
            print(the_class)
            c = Class.objects.get(school=t.school, standard=the_class)
            print(c)
            section = data['section']
            print(section)
            s = Section.objects.get(school=t.school, section=section)
            print(s)

            whole_class = data['whole_class']
            print('whole class = %s' % whole_class)
            if whole_class == 'false':
                student_list = data['student_list']
                print(student_list)
                print(type(student_list))

                # 29/08/2019 - when comes from Android, the student id list comes as an array. So we need to break it
                # into list. But from iOS, it comes as a proper list. So need not break it
                try:
                    students = ast.literal_eval(student_list)
                    print(students)
                except Exception as e:
                    print(
                        'exception 29082019-A from pic_share views.py %s %s' %
                        (e.message, type(e)))
                    print(
                        'looks the request has come from iOS, hence no need for ast.literal_eval'
                    )
                    students = student_list

            image_name = data['image_name']
            print(image_name)

            image = data['image']
            image_file = ContentFile(base64.b64decode(image),
                                     name=image_name.replace('@', ''))

            description = data['description']
            print(description)

            # save the image
            image_video = ImageVideo()
            image_video.location = image_file
            image_video.descrition = description
            image_video.teacher = t
            image_video.the_class = c
            image_video.section = s

            # long_link = 'https://storage.cloud.google.com/classup/classup2/media/prod/image_video/%s' % \
            #             image_name.replace('@', '')
            long_link = 'https://classup2.s3.us-east-2.amazonaws.com/media/prod/image_video/%s' % \
                        image_name.replace('@', '')
            print('long_link = %s' % long_link)
            short_link = long_link

            # prepare short link
            global_conf = GlobalConf.objects.get(pk=1)
            key = global_conf.short_link_api
            url = 'https://cutt.ly/api/api.php?'
            url += 'key=%s&short=%s' % (key, long_link)
            print('url for generating short link = %s' % url)
            try:
                req = urllib2.Request(url,
                                      headers={'User-Agent': "Magic Browser"})
                response = urllib2.urlopen(req)
                print('response for generating short link = %s' % response)
                outcome = json.loads(response.read())
                print('ouctome = ')
                print(outcome)
                status = outcome['url']['status']
                print('status = %i' % status)
                if status == 7:
                    short_link = outcome['url']['shortLink']
                    print('short_lint = %s' % short_link)
                    image_video.short_link = short_link
            except Exception as e:
                print('exception 15082019-A from pic_share views.py %s %s' %
                      (e.message, type(e)))
                print(
                    'failed to generate short link  for the image/video uploaded by %s'
                    % t)
                image_video.short_link = 'not available'
            try:
                image_video.save()
                print('saved the image uploaded by %s' % t)

                # now update with the SharedWith table
                if whole_class == 'true':
                    print('this image/video is shared with whole class %s-%s' %
                          (the_class, section))
                    students = Student.objects.filter(current_class=c,
                                                      current_section=s)
                    for student in students:
                        try:
                            shared = ShareWithStudents(image_video=image_video,
                                                       student=student,
                                                       the_class=c,
                                                       section=s)
                            shared.save()
                            print(
                                'saved the SharedWithStudent for %s of %s-%s' %
                                (student, the_class, section))
                            parent = student.parent.parent_name
                            message = 'Dear %s new pic uploaded. %s. Click %s' % (
                                parent, description, short_link)
                            print(message)
                            sms.send_sms1(student.school, teacher,
                                          student.parent.parent_mobile1,
                                          message, 'Share Pic')
                        except Exception as e:
                            print(
                                'exception 01082019-A from pic_share views.py %s %s'
                                % (e.message, type(e)))
                            print('failed to save SharedWithStudent object')
                else:
                    for an_item in students:
                        try:
                            student = Student.objects.get(pk=an_item)
                            shared = ShareWithStudents(image_video=image_video,
                                                       student=student,
                                                       the_class=c,
                                                       section=s)
                            shared.save()
                            print(
                                'saved the SharedWithStudent for %s of %s-%s. Now sending sms'
                                % (student, c, s))

                            parent = student.parent.parent_name
                            message = 'Dear %s new pic uploaded. %s. Click %s' % (
                                parent, description, short_link)
                            print(message)
                            sms.send_sms1(student.school, teacher,
                                          student.parent.parent_mobile1,
                                          message, 'Share Pic')
                        except Exception as e:
                            print(
                                'exception 02082019-A from pic_share views.py %s %s'
                                % (e.message, type(e)))
                            print('failed to save SharedWithStudent object')
                context_dict['status'] = 'success'
                context_dict['message'] = 'Media upload successful'
                print(image_video.location)
                try:
                    action = 'uploading image for %s-%s teacher %s' % (
                        the_class, section, t)
                    print(action)
                    log_entry(teacher, action, 'Normal', True)
                except Exception as e:
                    print('unable to crete logbook entry')
                    print(
                        'Exception 31072019-A from pic_share views.py %s %s' %
                        (e.message, type(e)))
                return JSONResponse(context_dict, status=200)
            except Exception as e:
                print(
                    'Exception 31072019-B from pic_share views.py = %s (%s)' %
                    (e.message, type(e)))
                print(
                    'error while trying to save the image/video uploaded by %s'
                    % t)
                context_dict['status'] = 'failed'
                context_dict[
                    'message'] = 'error while trying to save the image/video uploaded'
                return JSONResponse(context_dict, status=201)
        except Exception as e:
            print('failed to save image/video')
            print('Exception 02082019-B from pic_share views.py = %s (%s)' %
                  (e.message, type(e)))
            context_dict['status'] = 'failed'
            context_dict[
                'message'] = 'error while trying to save the image/video uploaded'
            return JSONResponse(context_dict, status=201)
示例#30
0
def process_attendance1(request, school_id, the_class, section, subject, d, m,
                        y, teacher):
    response_data = {}
    message_type = 'Attendance'

    if request.method == 'POST':
        log_entry(teacher, "Attendance Processing Started", "Normal", True)
        school = School.objects.get(id=school_id)

        # all of the above except date are foreign key in Attendance model. Hence we need to get the actual object
        c = Class.objects.get(school=school, standard=the_class)
        s = Section.objects.get(school=school, section=section)
        sub = Subject.objects.get(school=school, subject_name=subject)
        the_date = date(int(y), int(m), int(d))
        t = Teacher.objects.get(email=teacher)
        teacher_name = '%s %s' % (t.first_name, t.last_name)
        today = date.today()
        time_delta = today - the_date
        print(
            'this attendance taken by %s for class %s-%s for subject %s is %i days old'
            % (teacher_name, the_class, section, subject, time_delta.days))

        data = json.loads(request.body)
        print(data)
        absent = 0
        for key in data:
            student_id = data[key]
            student = Student.objects.get(id=student_id)
            student_name = '%s %s' % (student.fist_name, student.last_name)

            absent += 1

            # check to see if absence for this student for this date, class, section and subject has already
            #  been marked
            try:
                q = Attendance.objects.filter(date=the_date,
                                              the_class=c,
                                              section=s,
                                              subject=sub,
                                              student=student)

                # make an entry to database only it is a fresh entry
                #if q.count() == 0:
                if not Attendance.objects.filter(date=the_date,
                                                 the_class=c,
                                                 section=s,
                                                 subject=sub,
                                                 student=student).exists():
                    action = 'Absence marked for %s %s' % (student.fist_name,
                                                           student.last_name)
                    print(action)

                    attendance = Attendance(date=the_date)
                    attendance.the_class = c
                    attendance.section = s
                    attendance.subject = sub
                    attendance.student = student
                    attendance.taken_by = t

                    attendance.save()
                    log_entry(teacher, action, "Normal", True)
                    action = 'Starting to send sms to parents of  ' + student.fist_name + ' ' + student.last_name
                    log_entry(teacher, action, "Normal", True)
                    # send sms to the parents of absent students
                    m1 = ''
                    m2 = ''
                    try:
                        p = student.parent
                        m1 = p.parent_mobile1
                        m2 = p.parent_mobile2
                    except Exception as e:
                        print('Exception occured during processing of: ')
                        print(student)
                        print('Exception3 from attendance views.py = %s (%s)' %
                              (e.message, type(e)))
                        log_entry(
                            teacher,
                            "Attendance Processing Error. Exception 3 from attendance views.py",
                            "Normal", True)

                    print("mobile1=" + m1)
                    print("mobile2=" + m2)

                    message = ''
                    configuration = Configurations.objects.get(school=school)
                    school_name = school.school_name
                    school_short_name = configuration.school_short_name

                    # 14/04/2018 - for collage students, SMS will be sent to students
                    institute_type = configuration.type

                    try:
                        parent_name = student.parent.parent_name
                        # prepare the message
                        action = 'Absence SMS Drafting for ' + parent_name + ' started'
                        log_entry(teacher, action, "Normal", True)

                        # 17/02/17 we are looking to use student first name in messages.
                        # However, some schools store entire name as first name. T
                        # his need to be checke and split first name if entire name is stored as first name
                        the_name = student.fist_name
                        if ' ' in student.fist_name:
                            (f_name, l_name) = the_name.split(' ')
                        else:
                            f_name = the_name
                        if institute_type == 'Collage':
                            message = 'Dear %s, you' % the_name
                        else:
                            message = 'Dear ' + parent_name + ', your ward ' + f_name

                        if institute_type == 'Collage':
                            if time_delta.days == 0:
                                message += ' are'
                            else:
                                message += ' were'
                        else:
                            if time_delta.days == 0:
                                message += ' is'
                            else:
                                message += ' was'

                        # if subject is main then we need to tell that student was absent
                        if subject == 'Main' or subject == 'main' or subject == 'MAIN':

                            message += ' absent on ' + str(d) + '/' + str(
                                m) + '/' + str(y)
                        else:
                            message += ' absent on ' + str(d) + '/' + str(m) + '/' + str(y) + \
                                       ' in the attendance of ' + subject
                        # 04/05/2017 - coaching classes does not require application for absence
                        if configuration.type != 'school':
                            message += '. Regards %s ' % school_short_name
                        else:
                            message += '. Please send an application (Ignore if already done). Regards, ' + school_short_name
                    except Exception as e:
                        print('Exception4 from attendance views.py = %s (%s)' %
                              (e.message, type(e)))
                        action = 'Error in drafting SMS for ' + parent_name + '. Exception 4 from attendance views.py'
                        log_entry(teacher, action, "Normal", True)

                    print(message)

                    # 10/02/2018 - absence SMS will not be sent if attendance is for a date older than 7 days
                    if time_delta.days < 7:
                        print(
                            'this attendance is recent. Hence SMS will be sent'
                        )
                        # for coaching classes and colleges we need to send sms for any kind of absence
                        if configuration.send_period_bunk_sms:

                            sms.send_sms1(school, teacher, m1, message,
                                          message_type)
                            action = 'Absence SMS sent to ' + parent_name
                            log_entry(teacher, action, "Normal", True)
                            if m2 != '':
                                if configuration.send_absence_sms_both_to_parent:
                                    sms.send_sms1(school, teacher, m2, message,
                                                  message_type)
                                    log_entry(teacher, action, "Normal", True)
                        else:
                            # for schools
                            # if this subject is NOT the main subject, then we will
                            # send sms only if the student was present
                            # in main attendance (means the student has BUNKED this class :)
                            if subject != 'Main' and subject != 'main' and subject != 'MAIN':
                                try:
                                    main = Subject.objects.get(
                                        school=school, subject_name='Main')
                                    q = Attendance.objects.filter(
                                        date=the_date,
                                        the_class=c,
                                        section=s,
                                        subject=main,
                                        student=student)
                                    if q.count() == 0:
                                        print(
                                            student.fist_name + ' ' +
                                            student.last_name +
                                            '  was not absent in Main attendance. '
                                            'Looks he has bunked this class...'
                                        )
                                        action = student.fist_name + ' ' + student.last_name
                                        action += ' found to be bunking the Class!!!'
                                        log_entry(teacher, action, "Normal",
                                                  True)
                                        if configuration.send_period_bunk_sms:
                                            sms.send_sms1(
                                                school, teacher, m1, message,
                                                message_type)
                                            action = 'Absence SMS sent to ' + student.parent.parent_name
                                            log_entry(teacher, action,
                                                      "Normal", True)
                                            if m2 != '':
                                                if configuration.send_absence_sms_both_to_parent:
                                                    sms.send_sms1(
                                                        school, teacher, m2,
                                                        message, message_type)
                                                    action = 'Absence SMS sent to Mrs. ' + student.parent.parent_name
                                                    log_entry(
                                                        teacher, action,
                                                        "Normal", True)
                                except Exception as e:
                                    action = 'Unable to send SMS to ' + student.parent.parent_name
                                    log_entry(teacher, action, "Normal", True)
                                    print('unable to send sms for ' + f_name)
                                    print(
                                        'Exception5 from attendance views.py = %s (%s)'
                                        % (e.message, type(e)))
                            else:
                                if configuration.send_absence_sms:
                                    sms.send_sms1(school, teacher, m1, message,
                                                  message_type)
                                    action = 'Absence SMS sent to ' + student.parent.parent_name
                                    log_entry(teacher, action, "Normal", True)
                                    if m2 != '':
                                        if configuration.send_absence_sms_both_to_parent:
                                            sms.send_sms1(
                                                school, teacher, m2, message,
                                                message_type)
                                            action = 'Absence SMS sent to Mrs. ' + student.parent.parent_name
                                            log_entry(teacher, action,
                                                      "Normal", True)
                    else:
                        print(
                            'this attendance is more than 7 days old. Hence not sending SMS'
                        )
                else:
                    print(
                        'absence for %s for %s in %s has already been marked.'
                        % (student_name, the_date, subject))
            except Exception as e:
                print('Exception6 from attendance views.py = %s (%s)' %
                      (e.message, type(e)))
                log_entry(
                    teacher,
                    "Absence was already marked. Exception 6 from attendance views.py",
                    "Normal", True)

        # 16/07/2019 we are implementing table to store daily attendance summaries.
        # So that download attendance summary is fast
        print('now storing the attendance summary for %s-%s of %s date %s' %
              (the_class, section, school, the_date))
        try:
            total = Student.objects.filter(current_class=c,
                                           current_section=s,
                                           active_status=True).count()
            print('total students in %s-%s of %s  = %i' %
                  (the_class, section, school, total))
            present = total - absent
            percentage = int(round((float(present) / float(total)) * 100, 0))
            print(percentage)
            print('students present on %s = %i' % (the_date, percentage))
            try:
                summary = DailyAttendanceSummary.objects.get(date=the_date,
                                                             the_class=c,
                                                             section=s,
                                                             subject=sub)
                summary.total = total
                summary.present = present
                summary.absent = absent
                summary.percentage = percentage
                summary.save()
                print(
                    'attendance summary for class %s-%s of %s date %s is updated'
                    % (the_class, section, school, the_date))
            except Exception as ex:
                print('exception 16072019-X from attendance views.py %s %s' %
                      (ex.message, type(ex)))
                summary = DailyAttendanceSummary(date=the_date,
                                                 the_class=c,
                                                 section=s,
                                                 subject=sub)
                summary.total = total
                summary.present = present
                summary.absent = absent
                summary.percentage = percentage
                summary.save()
                print(
                    'attendance summary for class %s-%s of %s date %s is stored'
                    % (the_class, section, school, the_date))
        except Exception as ex:
            print('exception 16072019-B from attendance views.py %s (%s)' %
                  (ex.message, type(ex)))
            print('failed in storing the attendance summary for %s-%s of %s' %
                  (the_class, section, school))
    response_data['status'] = 'success'
    log_entry(teacher, "Attendance Processing Complete", "Normal", True)
    return JSONResponse(response_data, status=200)