Esempio n. 1
0
def course_create(request, template_name='course/new_course.html'):
    if request.user.is_superuser:
        form = CourseForm(request.POST or None)
        if form.is_valid():
            with transaction.atomic():
                course = form.save()

                lesson = Lesson(title="Dummy lesson title", course_id=course.id)
                lesson.save()
                course.lesson = lesson

                exercise = Exercise(
                    course=course,
                    lesson=lesson,
                    title="Dummy exercise title",
                    description="",
                    test_method="",
                    code=""
                )
                exercise.save()

                course.main_exercise = exercise
                return HttpResponseRedirect(reverse('course:exercise_detail', kwargs={"course_id": exercise.course_id,
                                                                                      "lesson_id": exercise.lesson_id,
                                                                                      "exercise_id": exercise.pk}))
        return render(request, template_name, {'form': form})
    return TemplateResponse(request, '404.html', {})
Esempio n. 2
0
def create_lesson(request,course_id):
    course = Course.objects.get(pk=course_id)
    lesson = Lesson()
    lesson.owner = request.user
    lesson.course = course
    if request.method == 'POST':
        form = LessonForm(request.POST, request.FILES, instance=lesson)
        if form.is_valid():
            l = form.save()
        #return redirect('edit-lesson', lesson_id=i.pk)
        messages.add_message(request, messages.INFO, _('New lesson was created!'))
        return redirect('list-courses')
    else:
        form = LessonForm(instance=lesson)
    context = {'course': course, 'form': form}
    return render_to_response('create_lesson.html', context, RequestContext(request))
Esempio n. 3
0
 def save_lessons(self):
     path = DATA_DIR + '/' + self.dir + '/ru'
     onlydirs = [f for f in listdir(path) if isdir(join(path, f))]
     for d in onlydirs:
         lesson_yml_path = path + '/' + d + '/meta.yml'
         data = self.get_meta(lesson_yml_path)
         print(data)
         try:
             lesson = Lesson.objects.get(name_slug=d)
         except:
             lesson = Lesson()
         lesson.name_slug = d
         lesson.title = data['name']
         lesson.course = self.course
         lesson.save()
         print('Saving lesson...%s' % data['slug'])
         for f in data['files']:
             try:
                 topic = Topic.objects.get(lesson=lesson,
                                           filename=f['file'])
             except:
                 topic = Topic.objects.create(filename=f['file'],
                                              title=f['title'],
                                              lesson=lesson)
             topic.check_video(f)
             print('Saving topic %s' % f['file'])
Esempio n. 4
0
def save_lesson_complete(user_id, lesson_id):
    try:
        is_complete = LessonComplete.objects.get(user_id=user_id,
                                                 lesson_id=lesson_id)
    except LessonComplete.DoesNotExist:
        previous_lesson = LessonComplete(user_id=User(pk=user_id),
                                         lesson_id=Lesson(pk=lesson_id),
                                         complete=True)
        previous_lesson.save()
Esempio n. 5
0
def save_lesson_progress(user_id, lesson_id, part):
    try:
        previous_lesson = LessonProgress.objects.get(user_id=user_id,
                                                     lesson_id=lesson_id,
                                                     part=part)
    except LessonProgress.DoesNotExist:
        previous_lesson = LessonProgress(user_id=User(pk=user_id),
                                         lesson_id=Lesson(pk=lesson_id),
                                         part=part)
        previous_lesson.save()
Esempio n. 6
0
def populate():
    filename = '/home/jenyamalina/PycharmProjects/ISP/learnero/.downloader/stealer/stealer/spiders/courses.json'
    with open(filename, 'r') as f:
        datastore = json.load(f)
    for course in datastore:
        unit = Course.objects.filter(title=course['course']).first()
        # if unit is None:
        #     unit = Unit(title=course['module'])
        #     unit.save()

        lesson = Lesson(title=course['title'],
                        description=course['description'],
                        course=unit)

        lesson.save()

        url = course['url']
        img_temp = NamedTemporaryFile(delete=True)
        img_temp.write(urlopen(url).read())
        img_temp.flush()
        print(img_temp)
        lesson.image.save(f"image_{lesson.pk}.png", File(img_temp))
        lesson.save()

        unit.save()
Esempio n. 7
0
    def post(self, request, chapter_id):
        chapter = Chapter.objects.get(id=int(chapter_id))

        #index = request.POST.get('index', 0)
        #name = request.POST.get('name', u'')
        #url = request.POST.get('url', u'')
        #video = request.FILES.get('video')

        uploadlesson_form = UploadLessonForm(request.POST, request.FILES)

        if uploadlesson_form.is_valid():
            index = uploadlesson_form.cleaned_data['index']
            name = uploadlesson_form.cleaned_data['name']
            url = uploadlesson_form.cleaned_data['url']
            video = uploadlesson_form.cleaned_data['video']
            lesson = Lesson(chapter=chapter, index=index, name=name, url=url, video=video, time=3)

            lesson.save()

            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse(json.dumps(uploadlesson_form.errors), content_type='application/json')
    def forwards(self, orm):
        # Adding model 'Subscriber2Lesson'
        db.create_table(u'course_subscriber2lesson', (
            (u'id',
             self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('lesson', self.gf('django.db.models.fields.related.ForeignKey')(
                to=orm['course.Lesson'])),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(
                to=orm['main.UserProfile'])),
        ))
        db.send_create_signal(u'course', ['Subscriber2Lesson'])

        # Removing M2M table for field subscribers on 'Lesson'
        db.delete_table(db.shorten_name(u'course_lesson_subscribers'))
        owner = UserProfile.objects.get(pk=1)
        l = Lesson()
        l.name = 'Python course'
        l.is_active = True
        l.owner = owner
        l.save()
        print 'Lesson created!!!!!!'
Esempio n. 9
0
def lesson_progress_get(request):
    lesson_1 = False
    lesson_2 = False
    lesson_3 = False
    lesson_4 = False
    lesson_5 = False

    try:
        lesson_1 = LessonComplete(user_id=User(pk=request.user.pk),
                                  lesson_id=Lesson(number_of_lesson=1))
    except LessonComplete.DoesNotExist:
        try:
            lesson_1 = LessonProgress(user_id=User(pk=request.user.pk),
                                      lesson_id=Lesson(number_of_lesson=1),
                                      part=5)
        except LessonProgress.DoesNotExist:
            try:
                lesson_1 = LessonProgress(user_id=User(pk=request.user.pk),
                                          lesson_id=Lesson(number_of_lesson=1),
                                          part=4)
            except LessonProgress.DoesNotExist:
                try:
                    lesson_1 = LessonProgress(
                        user_id=User(pk=request.user.pk),
                        lesson_id=Lesson(number_of_lesson=1),
                        part=3)
                except LessonProgress.DoesNotExist:
                    try:
                        lesson_1 = LessonProgress(
                            user_id=User(pk=request.user.pk).pk,
                            lesson_id=Lesson(number_of_lesson=1),
                            part=2)
                    except LessonProgress.DoesNotExist:
                        try:
                            lesson_1 = LessonProgress(
                                user_id=User(pk=request.user.pk),
                                lesson_id=Lesson(number_of_lesson=1),
                                part=1)
                        except LessonProgress.DoesNotExist:
                            pass
        print(lesson_1, lesson_2, lesson_3, lesson_4, lesson_5)
        return lesson_1, lesson_2, lesson_3, lesson_4, lesson_5
Esempio n. 10
0
    def post(self, request):
        test = YouTubeTranscriptApi.get_transcript("R9rLCPW-eUI", languages=['id', 'en'])

        employee = Employee.objects.get(user=request.user)
        try:
            with transaction.atomic():
                if employee.status == 0:
                    raise PermissionDenied("user is not admin")

                courseName = request.data['course']['name']
                category = request.data['course']['category']
                img = request.data['course']['img']
                description = request.data['course']['description']
                price = request.data['course']["price"]
                learningPoint = request.data['course']["sylabus"]
                estimateTime = datetime.strptime(request.data['course']["estimate_time"], '%H:%M:%S')

                categoryObject = Topic.objects.filter(topic=category)
                if len(category) == 0 :
                    categoryObject = Topic(topic=category)
                else :
                    categoryObject = Topic.objects.filter(topic=category)

                course = Course(name=courseName, img=img, price =price, description=description, learningPoint=learningPoint, estimateTime=estimateTime)
                course.save()

                for i in categoryObject :
                    course.topic.add(i)


                
                for i in request.data['course']['section'] :
                    sectionTitle = i['title']
                    sectionDescription = i['description']
                    section = Section(title=sectionTitle, description=sectionDescription)
                    section.save()
                    course.section.add(section)

                    for j in i['lesson'] :
                        lessonTitle = j["title"]
                        lesson = Lesson(title=lessonTitle)
                        lesson.save()

                        allStep = []

                        for k in j["step"] :
                            stepTitle = k["title"]
                            stepType = k['type']

                            
                            if stepType == 0 :
                                stepContentText = k["content_text"]
                                stepTimeMinimum = datetime.strptime(k['time_minimum'], '%H:%M:%S')
                                step = Step(title=stepTitle, type=stepType, contentText=stepContentText, timeMinimum=stepTimeMinimum)
                                step.save()
                                allStep.append(step)
                            elif stepType == 1 :
                                stepContentVideo = k["content_video"]
                                stepTimeMinimum = datetime.strptime(k['time_minimum'], '%H:%M:%S')
                                step = Step(title=stepTitle, type=stepType, contentText=stepContentVideo,timeMinimum=stepTimeMinimum)
                                step.save()
                                allStep.append(step)


                        for k in range(len(allStep)) :
                            if len(allStep) == 1 :
                                continue
                            elif k == 0 :
                                allStep[k].nextID = allStep[k+1]
                                allStep[k].save()
                            elif k == (len(allStep) -1)  :
                                allStep[k].prevID = allStep[k - 1]
                                allStep[k].save()
                            else :
                                allStep[k].prevID = allStep[k - 1]
                                allStep[k].nextID = allStep[k+1]
                                allStep[k].save()

                        for k in allStep :
                            lesson.step.add(k)
                            course.totalStepAndQuiz += 1

                        section.lesson.add(lesson)

                    quizTitle = i['quiz']["title"]
                    quizDescription = i['quiz']["description"]
                    quizMinimumScore = i['quiz']["minimum_score"]
                    quizSection = QuizSection(title=quizTitle,
                                              description=quizDescription,
                                              minimumQuizScore=quizMinimumScore
                                              )
                    quizSection.save()
                    section.quizSection = quizSection
                    section.save()

                    for k in i['quiz']["quiz"] :
                        question = k["question"]
                        point = k['point']
                        quizChoice1Object = Choice(choice= k['choice_1']['choice'],
                                                   isRight= True if k['choice_1']["is_right"] == "true" else False )
                        quizChoice2Object = Choice(choice=k['choice_2']['choice'],
                                                   isRight=True if k['choice_2']["is_right"] == "true" else False)
                        quizChoice3Object = Choice(choice=k['choice_3']['choice'],
                                                   isRight=True if k['choice_3']["is_right"] == "true" else False)

                        quizChoice4Object = Choice(choice=k['choice_4']['choice'],
                                                   isRight=True if k['choice_4']["is_right"] == "true" else False)

                        quizChoice1Object.save()
                        quizChoice2Object.save()
                        quizChoice3Object.save()
                        quizChoice4Object.save()

                        quizObject = Quiz(question=question, choice1= quizChoice1Object, choice2=quizChoice2Object, choice3=quizChoice3Object, choice4=quizChoice4Object, point=point)
                        quizObject.save()
                        quizSection.quiz.add(quizObject)
                        course.totalStepAndQuiz += 1

                    course.section.add(section)
                    course.save()
                return Response({
                    "status" : 201,
                    "message" : "success",
                }, status=status.HTTP_201_CREATED)



        except PermissionDenied as e :
            return PermissionDeniedHandler(e)
Esempio n. 11
0
    def save_lessons(self):
        path = DATA_DIR + '/' + self.dir
        onlydirs = [f for f in listdir(path) if isdir(join(path, f))]
        for d in onlydirs:
            if d != 'code':
                lesson_yml_path = path + '/' + d + '/meta.yml'
                data = self.get_meta(lesson_yml_path)
                slug = '%s--%s' % (self.course.name_slug, d)
                try:
                    lesson = Lesson.objects.get(name_slug=slug)
                except:
                    lesson = Lesson()
                number = d.split('-')[0]

                lesson.name_slug = slug
                lesson.number = number
                try:
                    lesson.title = data['name']
                except:
                    lesson.title = 'Не определено!'
                    print('Ошибка в %s' % lesson_yml_path)
                    sys.exit()
                try:
                    lesson.desc = data['desc']
                except:
                    print('Error with desc in %s' % lesson_yml_path)

                try:
                    lesson.created_at = data['created']
                except:
                    lesson.created_at = '2000-01-01'

                lesson.meta_keywords = data['meta_keywords']
                lesson.meta_title = data['meta_title']
                lesson.meta_description = data['meta_description']
                lesson.course = self.course
                lesson.save()
                ## add tags
                if 'tags' in data:
                    tags = data['tags'].split(' ')
                    for tag in tags:
                        Tag.objects.add_tag(lesson, tag)
                print('Saving lesson...%s' % data['slug'])
                for f in data['files']:
                    try:
                        topic = Topic.objects.get(lesson=lesson,
                                                  filename=f['file'])
                    except Exception as e:
                        topic = Topic.objects.create(filename=f['file'],
                                                     course=self.course,
                                                     title=f['title'],
                                                     lesson=lesson,
                                                     created_at='2000-01-01')
                    ## make order
                    try:
                        order = f['order']
                        topic.order = order
                        topic.save()
                    except:
                        pass

                    try:
                        order = f['created']
                        topic.created_at = f['created']
                        topic.save()
                    except:
                        pass

                    print('Saving topic %s' % f['file'])
                    topic.check_video(f)