def create(): form = LessonForm() if form.validate_on_submit(): print request.form #4/0 lesson = Lesson() lesson.title = request.form.get('title') lesson.time = request.form.get('time') lesson.audience = request.form.get('audience') lesson.goals = request.form.get('goals') lesson.summary = request.form.get('summary') session.add(lesson) session.flush() for index, step_entry in enumerate(form.steps.entries): step = Step() step.title = step_entry.title.data step.body = step_entry.body.data step.order = index step.lesson = lesson session.add(step) session.flush() session.commit() return redirect(url_for('view', uid=lesson.id)) return render_template('create.html', form=form)
def create(): form = LessonForm() if form.validate_on_submit(): print request.form #4/0 lesson = Lesson() lesson.title = request.form.get('title') lesson.time = request.form.get('time') lesson.audience = request.form.get('audience') lesson.goals = request.form.get('goals') lesson.summary = request.form.get('summary') session.add(lesson) session.flush() for index,step_entry in enumerate(form.steps.entries): step = Step() step.title = step_entry.title.data step.body = step_entry.body.data step.order = index step.lesson = lesson session.add(step) session.flush() session.commit() return redirect(url_for('view', uid=lesson.id)) return render_template('create.html', form=form)
def set_lesson(request): ids = request.GET.get('lesson', '').split(',') del ids[len(ids)-1] lessons = get_list_or_404(Lesson, id__in=ids, teacher=request.user, attendance__grade=request.user.current_grade) for lesson in lessons: form = LessonForm(request.GET, instance = lesson) if form.is_valid(): form.save() return HttpResponse('ok')
def set_lesson(request): ids = request.GET.get('lesson', '').split(',') del ids[len(ids) - 1] lessons = get_list_or_404(Lesson, id__in=ids, teacher=request.user, attendance__grade=request.user.current_grade) for lesson in lessons: form = LessonForm(request.GET, instance=lesson) if form.is_valid(): form.save() return HttpResponse('ok')
def lessonEdit(request, mode, id = 0): render = {} if request.method == 'GET': if mode == 'edit': lesson = get_object_or_404(Lesson, id = id, teacher = request.user) render['form'] = LessonForm(instance = lesson) grades_id = [] for connection in Connection.objects.filter(teacher = request.user): grades_id.append(connection.grade.id) render['form'].fields['grade'].queryset = Grade.objects.filter(id__in = grades_id) render['lesson_id'] = id return render_to_response('marks/teacher/lesson.html', render, context_instance = RequestContext(request)) elif mode == 'delete': lesson = get_object_or_404(Lesson, id = id, teacher = request.user) lesson.delete() return HttpResponseRedirect('/marks/lesson/') else: render['form'] = LessonForm() grades_id = [] for connection in Connection.objects.filter(teacher = request.user): grades_id.append(connection.grade.id) render['form'].fields['grade'].queryset = Grade.objects.filter(id__in = grades_id) return render_to_response('marks/teacher/lesson.html', render, context_instance = RequestContext(request)) else: form = LessonForm(request.POST, request.FILES) grades_id = [] for connection in Connection.objects.filter(teacher = request.user): grades_id.append(connection.grade.id) form.fields['grade'].queryset = Grade.objects.filter(id__in = grades_id) if mode == 'edit': if form.is_valid(): lesson = get_object_or_404(Lesson, id = id, teacher = request.user) form = LessonForm(request.POST, request.FILES, instance = lesson) form.save() return HttpResponseRedirect('/marks/lesson/') else: render['form'] = form return render_to_response('marks/teacher/lesson.html', render, context_instance = RequestContext(request)) else: if form.is_valid(): lesson = form.save(commit = False) lesson.teacher = request.user lesson.subject = request.user.current_subject lesson.save() form.save_m2m() return HttpResponseRedirect('/marks/lesson/') else: render['form'] = form return render_to_response('marks/teacher/lesson.html', render, context_instance = RequestContext(request))
def new_lesson(self): form = LessonForm() if request.method == 'POST': course_id = form.course_id.data course_id = ObjectId(course_id) if form.validate() == False: data = self.course_data(course_id) data['new_lesson_form'] = form data['new'] = 1 return render_template('instructor/course.html', data=data) else: #return jsonify(course_id) #course_id = '5a5e2612a8af96b319f84dce' #data = self.course_data(str(course_id)) #duration = request.form['duration'] id = self.newLesson.add(form.title.data, form.video_url.data, form.description.data, form.duration.data, course_id) return redirect(url_for('instructor_course', courseId=course_id)) return redirect(url_for('instructor_dashboard'))
def lesson_admin_update(request, lesson_id, prefix): if request.is_ajax(): form = LessonForm(request.POST) if prefix == 'None' else LessonForm(request.POST, prefix=prefix) if form.is_valid(): try: lesson = Lesson.objects.get(pk=lesson_id) lesson.course = form.cleaned_data['course'] lesson.description = form.cleaned_data['description'] lesson.name = form.cleaned_data['name'] lesson.save() return HttpResponse('OK') except ObjectDoesNotExist: # create new object position = None if Lesson.objects.count() > 0: lesson = Lesson.objects.order_by('-position').all()[0] position = lesson.position else: position = 1 newlesson = Lesson() newlesson.course = form.cleaned_data['course'] newlesson.name = form.cleaned_data['name'] newlesson.description = form.cleaned_data['description'] newlesson.position = position newlesson.save() response = {'created_object_id': newlesson.pk} return HttpResponse(json.dumps(response), mimetype="application/json") else: errors_dict = {} if form.errors: for error in form.errors: e = form.errors[error] field = prefix+"-"+error; errors_dict[field] = unicode(e) print errors_dict return HttpResponseBadRequest(json.dumps(errors_dict)) else: return HttpResponseNotFound('You do not have permission to access this page!')
def update_lesson(self): form = LessonForm() data = {} if request.method == 'POST': lesson_id = form.lesson_id.data lesson_id = ObjectId(lesson_id) lesson = self.newLesson.get_lesson_by_id(lesson_id) if form.validate() == True: result = self.newLesson.update(lesson_id, form.title.data, form.video_url.data, form.description.data, form.duration.data) if result == 'OK': flash('1') else: flash('0') #return jsonify(str(result)) return redirect(url_for('instructor_edit_lesson', lessonId=lesson_id)) else: return redirect(url_for('instructor_edit_lesson', lessonId=lesson_id)) return redirect(url_for('instructor_dashboard'))
def course_secretary_page(secretaryID): """Show general secretary page""" secretary = Secretary.query.get_or_404(secretaryID) if secretary.course: return render_template("sec_course_page.html", secretary=secretary, form=LessonForm()) else: return redirect("/secretary")
def course(self, course_id): if self.loggedIn != True: return redirect(url_for('instructor_login')) data = self.course_data(course_id) data['new_course_form'] = CourseForm() data['new_course_form'].instructor_id.data = data['instructor']['_id'] data['new_lesson_form'] = LessonForm() data['new_lesson_form'].course_id.data = course_id #return jsonify(len(similar_courses)) if data['course']: return render_template("instructor/course.html", data=data) else: return redirect(url_for('index'))
def edit_lesson(self, lesson_id): form = LessonForm() data = {} lesson = self.newLesson.get_lesson_by_id(ObjectId(lesson_id)) course = self.newCourse.get_course_by_id(lesson['course_id']) data['edit_lesson_form'] = form data['edit_lesson_form'].lesson_id.data = lesson_id data['edit_lesson_form'].title.data = lesson['title'] data['edit_lesson_form'].video_url.data = lesson['video_url'] data['edit_lesson_form'].description.data = lesson['description'] data['edit_lesson_form'].duration.data = lesson['duration'] data['lesson'] = lesson data['course'] = course data['instructor'] = self.newInstructor.get_instructor_by_name(session['instructor']['name']) return render_template('instructor/edit_lesson.html', data=data)
def index(request): ''' Очень обширная страница, необходимо сделать разделение. ''' render = {} if request.user.type == 'Parent': start = date.today() - timedelta(weeks = 2) end = date.today() + timedelta(days = 1) if request.method == 'GET': render['form'] = form = StatForm() else: render['form'] = form = StatForm(request.POST) if form.is_valid(): start = form.cleaned_data['start'] end = form.cleaned_data['end'] render.update(request.user.current_pupil.get_all_marks(start, end)) elif request.user.type == 'Teacher': import demjson if request.GET.get('set_current_grade', False): grade = get_object_or_404(Grade, id = request.GET.get('set_current_grade')) if grade not in request.user.grades.all(): raise Http404(u'Нет такого класса') request.user.current_grade = grade request.user.save() render['lesson_form'] = LessonForm() if request.GET.get('set_lesson', False): lesson = get_object_or_404(Lesson, id = int(request.GET.get('lesson', 0)), teacher = request.user) form = LessonForm(request.GET, instance = lesson) if form.is_valid(): form.save() return HttpResponse('ok') if request.GET.get('get_lesson_info', False): lesson = get_object_or_404(Lesson, id = int(request.GET.get('lesson', 0)), teacher = request.user) return HttpResponse(demjson.encode({'task': lesson.task or '', 'topic': lesson.topic or ''})) if request.GET.get('set_mark', False): from templatetags.marks_chart import get_mark pupil = get_object_or_404(Pupil, id = int(request.GET.get('pupil', 0)), grade = request.user.current_grade) lesson = get_object_or_404(Lesson, id = int(request.GET.get('lesson', 0)), teacher = request.user) mark = unicode(request.GET.get('mark', 0)).lower() Mark.objects.filter(pupil = pupil, lesson = lesson).delete() m = Mark(pupil = pupil, lesson = lesson) tr_id = 'p-%d-%d' % (pupil.id, lesson.id) if mark not in ['1', '2', '3', '4', '5', 'n', u'н', '']: return HttpResponse(demjson.encode({'id': tr_id, 'mark': 'no'})) if mark == '': return HttpResponse(demjson.encode({'id': tr_id, 'mark': ''})) if mark in [u'n', u'н']: m.absent = True else: m.mark = int(mark) m.save() return HttpResponse(demjson.encode({'id': tr_id, 'mark': get_mark(pupil, lesson), 'mark_value': str(m).strip(), 'mark_type': m.get_type() }, encoding = 'utf-8')) from pytils import dt if not request.user.current_grade: if request.user.get_grades(): request.user.current_grade = request.user.get_grades()[0] request.user.save() else: messages.error(request, u'К вам не привязано классов') return HttpResponseRedirect('/') request.user.current_grade.get_pupils_for_teacher_and_subject( request.user, request.user.current_subject ) try: day, month, year = request.GET.get('date', '').split('.') date_start = date(day = day, month = month, year = year) except ValueError: date_start = date.today() lessons_range = [] render['monthes'] = monthes = {} for i in xrange(1, 13): monthes[i] = ('', 0) kwargs = { 'subject': request.user.current_subject, 'grade': request.user.current_grade } conn = Connection.objects.filter(teacher = request.user, **kwargs) if not conn: raise Http404('No connections') conn = conn[0] if conn.connection != '0': kwargs['group'] = conn.connection kwargs4lesson = {} for i in xrange(14, -1, -1): d = date_start - timedelta(days = i) kwargs['workday'] = str(d.weekday()+1) if UsalTimetable.objects.filter(**kwargs): kwargs4lesson = {'teacher': request.user, 'date': d, 'subject': request.user.current_subject} groups = {} for lesson in UsalTimetable.objects.filter(**kwargs): groups[lesson.group] = groups.get(lesson.group, 0) + 1 groups = groups.values() if Lesson.objects.filter(grade = request.user.current_grade, **kwargs4lesson).count() != max(groups): for j in xrange(max(groups) - Lesson.objects.filter(**kwargs4lesson).count()): t = Lesson(**kwargs4lesson) t.save() t.grade.add(request.user.current_grade) t.save() resultdates = ResultDate.objects.filter(date = d, grades = request.user.current_grade) if resultdates: resultdate = resultdates[0] kwargs4lesson = { 'resultdate': resultdate, 'grade': request.user.current_grade, 'subject': request.user.current_subject, 'teacher': request.user } if not Lesson.objects.filter(**kwargs4lesson): del kwargs4lesson['grade'] lesson = Lesson(topic = resultdate.name, date = resultdate.date, **kwargs4lesson) lesson.save() lesson.grade.add(request.user.current_grade) lesson.save() if len(kwargs4lesson) == 0: raise Http404(u'Нет расписания') del kwargs4lesson['date'] kwargs4lesson['date__gte'] = date_start - timedelta(days = 15) for lesson in Lesson.objects.filter(**kwargs4lesson).order_by('date'): monthes[lesson.date.month] = (dt.ru_strftime(u'%B', lesson.date), monthes[lesson.date.month][1] + 1) lessons_range.append(lesson) for i in monthes.keys(): if monthes[i][1] == 0: del monthes[i] render['lessons'] = lessons_range return render_to_response( '~marks/%s/index.html' % request.user.type.lower(), render, context_instance = RequestContext(request))
def index(request): ''' Очень обширная страница для выставления и просмотра оценок ''' def _get_month_key(dt): return int("%d%s" % (dt.year, str(dt.month).rjust(2, "0"))) render = {} if request.user.type == 'Parent': start = date.today() - timedelta(weeks=2) end = date.today() + timedelta(days=1) if request.method == 'GET': render['form'] = form = StatForm() else: render['form'] = form = StatForm(request.POST) if form.is_valid(): start = form.cleaned_data['start'] end = form.cleaned_data['end'] render.update(request.user.current_pupil.get_all_marks(start, end)) elif request.user.type == 'Teacher': import demjson if request.GET.get('set_current_grade', False): grade = get_object_or_404(Grade, id=request.GET.get( 'set_current_grade', 0)) if grade not in request.user.grades.all(): raise Http404(u'Нет такого класса') request.user.current_grade = grade request.user.save() if request.GET.get('set_current_subject', False): subject = get_object_or_404(Subject, id=request.GET.get( 'set_current_subject', 0)) if subject not in request.user.subjects.all(): raise Http404(u'Нет такого предмета') request.user.current_subject = subject request.user.save() if not request.user.current_grade: if request.user.get_grades_for_marks(): request.user.current_grade = request.user.get_grades_for_marks( )[0] else: messages.error(request, u'К вам не прикреплено классов') return render_to_response( '~marks/%s/index.html' % request.user.type.lower(), render, context_instance=RequestContext(request)) render['lesson_form'] = LessonForm() try: request.user.current_grade.get_pupils_for_teacher_and_subject( request.user, request.user.current_subject) except PlaningError: messages.error(request, u'В выбранном классе нет учеников') return render_to_response('~marks/%s/index.html' % request.user.type.lower(), render, context_instance=RequestContext(request)) from pytils import dt date_start = date.today() - timedelta(days=15) date_end = date.today() + timedelta(days=1) render['stat_form'] = form = StatForm(request.GET) if form.is_valid(): date_start = form.cleaned_data['start'] date_end = form.cleaned_data['end'] else: render['stat_form'] = StatForm() lessons_range = [] render['monthes'] = monthes = {} month = date.today() - timedelta(days=365) while month < date.today() + timedelta(days=30): monthes[_get_month_key(month)] = ('', 0) month += timedelta(weeks=4) kwargs = { 'subject': request.user.current_subject, 'grade': request.user.current_grade } conn = Connection.objects.filter(teacher=request.user, **kwargs) if not conn: messages.error(request, u'Нет связок в выбранном сочетании предмет-класс') return render_to_response('~marks/%s/index.html' % request.user.type.lower(), render, context_instance=RequestContext(request)) kwargs4lesson = { 'teacher': request.user, # 'attendance__subject': request.user.current_subject, 'date__gte': date_start, # 'attendance__grade': request.user.current_grade, 'date__lte': date_end } args = [Q(attendance__group=c.connection) for c in conn] args.append(Q(attendance__group="0")) args.append(Q(attendance=None)) filter_arg = \ Q(attendance__subject=request.user.current_subject, attendance__grade=request.user.current_grade) \ | Q(resultdate__grades=request.user.current_grade, grade=request.user.current_grade, subject=request.user.current_subject) # filter_args.append(Q(attendance__subject=request.user.current_subject, attendance__grade=request.user.current_grade)) # filter_args.append(Q(resultdate__subject=request.user.current_subject, resultdate__grade=request.user.current_grade)) last_col = [] last_date = None for lesson in Lesson.objects.filter(reduce(lambda x, y: x | y, args), filter_arg, **kwargs4lesson).order_by('date'): new_range = lesson.attendance==None or not lesson.attendance.subject.groups or \ (len(last_col) == conn.count() and conn[0].connection != "0") or \ lesson.attendance.group == '0' or last_date != lesson.date if new_range: monthes[_get_month_key(lesson.date)] = (dt.ru_strftime( u'%B', lesson.date), monthes[_get_month_key(lesson.date)][1] + 1) if len(last_col): lessons_range.append(last_col) last_col = [] last_col.append(lesson) last_date = lesson.date if len(last_col): lessons_range.append(last_col) for i in monthes.keys(): if monthes[i][1] == 0: del monthes[i] render['lessons'] = lessons_range return render_to_response('~marks/%s/index.html' % request.user.type.lower(), render, context_instance=RequestContext(request))