def create_course(self): course = Course() course.title= "just_created" course.description = "course_desc" course.instructor_id = 1 course.save() return course
def test_lecture_cant_have_not_youtube_url(self): course = Course() course.title = "Yet another title" course.save() week = Week() week.number = 1 week.course = course week.save() data = {"title": "My lecture", "week": week, "order_id": 1, "embed_video_url": "https://www.youtube.com/embed/lXn7XKLA6Vg", } # For easy use _assert_true = self.assertTrue _assert_false = self.assertFalse urls = ( ("http://habrahabr.ru", _assert_false), ("https://www.google.com.ua/", _assert_false), ("https://www.youtube.com/watch?v=lXn7XKLA6Vg", _assert_true) ) for url, suggested_func in urls: data["video_url"] = url lecture = NewLectureForm(data=data) suggested_func(lecture.is_valid())
def create_course_view(request): if request.method == 'POST': form = NewCourseForm(request.POST) if form.is_valid(): new_course = Course() new_course.title = request.POST['title'] new_course.short_description = request.POST['short_desc'] new_course.full_description = request.POST['full_desc'] new_course.save() return redirect(reverse('courses:course_page', args=(new_course.id,))) else: form = NewCourseForm() return render(request, 'new_course.html', {"new_course_form": form})
def mit(debug=False): base_url = "http://ocw.mit.edu" r = requests.get(base_url + "/courses/") soup = BeautifulSoup(r.text) for course_list in soup("div",{"class":"course_list"}): category_name = str(course_list("div",{"class":"table_head"})[0]("a")[0].string).lower() for row in course_list("tr",{"class":"row"}) + course_list("tr",{"class":"alt-row"}): course_id = row("td")[2].string school_name = "mit" try: school = School.objects.filter(name__icontains=school_name)[0] except: school = School.objects.create(name=school_name) try: category = Category.objects.get(name=category_name) except: category = Category.objects.create(name=category_name) try: m = Course.objects.filter(type="mit").filter(course_id=str(course_id))[0] except: m = Course() material_names = [a['alt'] for a in row("td")[1]("a")] materials = [] for name in material_names: try: material = Material.objects.get(name=name) except: material = Material.objects.create(name=name) materials.append(material) m.title = row("td")[3]("a")[0]("u")[0].string m.link = base_url + row("td")[3]("a")[0]['href'] m.type = "mit" m.course_id = course_id m.school = school m.save() m.categories = [category] m.materials = materials m.save() if debug: print m
def test_update_courses_valid(self): course = Course() course.title = "just_created" course.description = "course_desc" course.instructor_id = 1 course.save() data = {'title': 'new_title', 'description': 'new desc'} response = self.get_instructor_owner.put(reverse( 'courses_api:course-detail', args=[course.id]), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['title'], data['title']) self.assertEqual(response.data['description'], data['description'])
def coursera(debug=False): r = requests.get("https://www.coursera.org/maestro/api/topic/list?full=1") data = json.loads(r.text) for course in data: course_id = course['id'] school_name = course['universities'][0]['name'].lower() category_names = [a['name'].lower() for a in course['categories']] categories = [] try: school = School.objects.filter(name__icontains=school_name)[0] except: school = School.objects.create(name=school_name) for category_name in category_names: try: category = Category.objects.get(name=category_name) except: category = Category.objects.create(name=category_name) categories.append(category) try: m = Course.objects.filter(type="coursera").filter(course_id=course_id)[0] except: m = Course() material_names = ["Assignments and solutions","Projects and examples","Multimedia content","Exams and solutions"] materials = [] for name in material_names: try: material = Material.objects.get(name=name) except: material = Material.objects.create(name=name) materials.append(material) m.title = course['name'] m.link = course['social_link'] m.image_url = course['small_icon'] m.course_id = course_id m.type = "coursera" m.school = school m.save() m.categories = categories m.materials = materials m.save() if debug: print m
def test_course_can_holds_weeks_and_lectures(self): course = Course() course.title = "A little title" course.save() week = Week() week.course = course week.number = 1 week.save() lecture = Lecture() lecture.title = "My lecture" lecture.video_url = "https://www.youtube.com/watch?v=lXn7XKLA6Vg" lecture.week = week lecture.order_id = 1 lecture.save() self.assertEqual(week, Week.objects.get(course=course)) self.assertEqual(lecture, Lecture.objects.get(week=week))
def edx(debug=False): base_url = "https://www.edx.org" r = requests.get(base_url + "/courses") soup = BeautifulSoup(r.text) for column in soup("section", {"class":"university-column"}): for course in column("article",{"class":"course"}): course_id = "/".join(course['id'].split("/")[:-1]) school_name = course['id'].split("/")[0][:-1].lower() try: school = School.objects.filter(name__icontains=school_name)[0] except: school = School.objects.create(name=school_name) try: m = Course.objects.filter(type="edx").filter(course_id=course_id)[0] except: m = Course() material_names = ["Assignments and solutions","Projects and examples","Multimedia content","Exams and solutions"] materials = [] for name in material_names: try: material = Material.objects.get(name=name) except: material = Material.objects.create(name=name) materials.append(material) m.title = " ".join(course("header")[0]("h2")[0].get_text().split(" ")[1:]) m.link = base_url + course("a")[0]['href'] m.image_url = base_url + course("img")[0]['src'] m.type = "edx" m.course_id = course_id m.school = school m.save() m.materials = materials m.save() if debug: print m
print len(tempset) # tempset is now just the unique CCNs. We'll make a Course instance for each by # getting the first result of a query for Offerings with that CCN for t in tempset: o = Offering.objects.filter(ccn=t)[:1] # o looks like a single object but is actually a queryset consisting of one record. # To get the first actual object in it, use o[0] offering = o[0] print print offering # Create a Course record based on that course = Course() course.title = offering.title course.ccn = offering.ccn course.cstring = offering.cstring course.units = offering.units course.type = offering.type course.description = offering.description course.restrictions = offering.restrictions course.save() # Programs is many to many. Loop through and re-create for p in offering.programs.all(): course.programs.add(p) # title = models.CharField(max_length=384) # ccn = models.CharField('CCN',max_length=384, blank=True) # cstring = models.ForeignKey(Cstring,verbose_name='Course String',help_text="e.g. J-200, but without the J")
# save all subjects with open('subjects.txt') as f: subjects_json = json.load(f) for subject in subjects_json: s = Subject() s.name = subjects_json[subject]['SubjectName'] s.abbreviation = subjects_json[subject]['SubjectAbbreviation'] s.save() # save all courses and courses with open('classes.txt') as f: classes_json = json.load(f) for c in classes_json: course = classes_json[c]['Course'] new_course = Course() new_course.subject = Subject.objects.filter( abbreviation=course['Subject']['SubjectAbbreviation'])[0] new_course.title = course['Title'] new_course.number = course['CourseNumber'] new_course.save() sections = classes_json[c]['Sections'] for s in sections: new_course_section = CourseSection() new_course_section.course = new_course new_course_section.section_type = sections[s]['Type'] new_course_section.crn = sections[s]['CRN'] new_course_section.meetings = sections[s]['Meetings'] new_course_section.save()
course_map = {} courses_request = requests.get('http://api.purdue.io/odata/Courses') courses_request_data = dict(courses_request.json()) for course in courses_request_data['value']: if subject_map.get(course['SubjectId']) is not None: course_map[course['CourseId']] = subject_map.get(course['SubjectId']) course_map[course['CourseId']]['Title'] = course['Title'] course_map[course['CourseId']]['Number'] = course['Number'] current_term_courses = {} current_term_classes = {} classes_request = requests.get('http://api.purdue.io/odata/Classes') classes_request_data = dict(classes_request.json()) for c in classes_request_data['value']: if c['TermId'] == CURRENT_TERM and c['CampusId'] == CAMPUS: current_term_classes[c['ClassId']] = course_map.get(c['CourseId']) current_term_classes[c['ClassId']]['CourseId'] = c['CourseId'] if current_term_courses.get(c['CourseId']) is None: current_term_courses[c['CourseId']] = course_map.get(c['CourseId']) f = open('courses.txt', 'w') f.write(str(current_term_courses)) for course in current_term_courses: c = Course() c.subject = Subject.objects.get( abbreviation=current_term_courses[course]['Abbreviation']) c.title = current_term_courses[course]['Title'] c.number = current_term_courses[course]['Number'] c.save()
python manage.py startapp courses #id is automatically added in django python manage.py makemigrations # python manage.py makemigrations courses (to be more specific) python manage.py migrate python manage.py shell from courses.models import Course Course.objects.all() c = Course() c.title = "Python Basics" c.description = "Learn the basics of python" c.save() Course(title="Python Collections", description="Learn abouyt lists , dict and tuples").save() Course.objects.create(title="Object Oriented Python", description="Learn about python's classes") #python manage.py shell opens a Python shell with Django's configuration already loaded. #Model.save() will save an in-memory instance of a model to the database. #Model.create() will save an in-memory instance of a model to the database and return the newly-created object. #Model.filter(attribute=value) will get a QuerySet of all instances of the Model that match the attribute values. You can change these values with other comparisons, too, like gte or in. Find out more here #include() allows you to include a list of URLs from another module. It will accept the variable name or a string with a dotted path to the default urlpatterns variable. #If you don't have include() in your urls.py (more recent versions of Django have removed it), add it to the import line that imports url. That line will now look like from django.conf.urls import url, include. #This is the Comprehensions Workshop that's mentioned in the video. Comprehensions are a great way of doing quick work with iterables.