def new_course(request, tag): form=CourseForm(initial={'tag':tag, 'owner':request.user}) if request.method == 'POST': if form.validate(request.form): form.save(crud=CRUD.Create) return redirect('') return render_to_response('tasteofhome/new_course.html', {'form': form.as_widget()})
def assign_course(id): """ Assign a student to a course for a given year """ check_admin() course = Course.query.get_or_404(id) # prevent admin from being assigned a course if course.is_admin: abort(403) form = CourseForm(obj=course) if form.validate_on_submit(): course.department = form.department.data course.role = form.role.data course.student = form.student.data course.enrolment = form.enrolment.data db.session.add(course) db.session.commit() flash('You have successfully assigned a student, department and role.') # redirect to the roles page return redirect(url_for('admin.list_courses')) return render_template('admin/courses/course.html', course=course, form=form, title='Assign Course')
def edit_course(request, course): form=CourseForm(instance=course, initial={'owner': course.owner}) if request.method == 'POST': if form.validate(request.form): form.save(crud=CRUD.Update) return return render_to_response('tasteofhome/edit_course.html', {'tag': tag, 'form': form})
def create_course( request, course_id=None ): #Firstst of all we need to make user that non-institutions can't create courses if request.user.user_type == "u": return HttpResponseRedirect('/ticwiapp/desktop') #Prepares the information to update or create a new course. #if id: # instance = get_object_or_404(Course, id=course_id) # form = CourseForm(request.POST or None, instance=instance) # if form.is_valid(): # form.update() # return HttpResponseRedirect('/ticwiapp/get/') # course = Course.objects.get(id=id) # dictionary = model_to_dict(course, fields=[], exclude=[]) # form = forms.CourseForm(dictionary) #else: if request.POST: form = CourseForm(request.POST) if form.is_valid(): a = form.save( commit = False ) a.user = request.user a.save() return HttpResponseRedirect('/ticwiapp/desktop') else: form = CourseForm() args = {} args.update(csrf(request)) args['form'] = form args['full_name'] = request.user.username return render_to_response('create_course.html', args)
def updateSyllabus(request, department, class_number, year, semester, section, sid): user = request.user c = getClassObject(department, class_number, year, semester, section, user) s = get_object_or_404(CourseContent, pk=sid) message = '' classUrl = getClassUrl(c) #Updates the syllabus if request.method == 'POST': course = CourseContent(id=sid, cid=c, created_on=s.created_on, was_updated=1, updated_on=datetime.datetime.now() ) form = CourseForm(request.POST, instance=course) if form.is_valid(): form.save() message = 'You have successfully updated the syllabus' else: #Initializes the form with existing syllabus information course = CourseContent.objects.get(cid=c.cid) form = CourseForm(initial={'officeHrs': course.officeHrs, 'officeLocation': course.officeLocation, 'phoneNumber': course.phoneNumber, 'TaOfficeLocation': course.TaOfficeLocation, 'TaOfficeHrs': course.TaOfficeHrs, 'lectTime': course.lectTime, 'prereq': course.prereq, 'books': course.books, 'topics': course.topics, 'markingScheme': course.markingScheme, 'academicHonesty': course.academicHonesty, 'additionalInfo': course.additionalInfo,}) content = getContent(c, user) content['form'] = form content['classUrl'] = classUrl content['message'] = message return render_to_response('instructor/syllabus.html', content, context_instance=RequestContext(request))
def api_add_course(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): c = form.save(commit=False) if int(request.POST["lecturer_id"]) == -1: lec = Lecturer.objects.get_or_create(title=request.POST["lecturer_title"], name=request.POST["lecturer_name"], department=request.POST["lecturer_dept"], email=request.POST["lecturer_email"], uni=University.objects.get(id=int(request.POST["uni"])))[0] lec.save() c.lecturer = lec else: c.lecturer = Lecturer(id=int(form.data["lecturer_id"])) c.save() return course(request, c.id) else: print form.errors return add_course(request) return add_course(request)
def api_add_course(request): if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): c = form.save(commit=False) if int(request.POST["lecturer_id"]) == -1: lec = Lecturer.objects.get_or_create( title=request.POST["lecturer_title"], name=request.POST["lecturer_name"], department=request.POST["lecturer_dept"], email=request.POST["lecturer_email"], uni=University.objects.get(id=int(request.POST["uni"])))[0] lec.save() c.lecturer = lec else: c.lecturer = Lecturer(id=int(form.data["lecturer_id"])) c.save() return course(request, c.id) else: print form.errors return add_course(request) return add_course(request)
def syllabus(request, department, class_number, year, semester, section): user = request.user c = getClassObject(department, class_number, year, semester, section, user) message = '' classUrl = getClassUrl(c) #Form that has defined fields for prof to fill out to create a syllabus if request.method == 'POST': content = CourseContent(cid=c, created_on=datetime.datetime.now(), was_updated=0, updated_on=datetime.datetime.now() ) form = CourseForm(request.POST, instance=content) if form.is_valid(): form.save() message = 'You have successfully created a syllabus' else: #If form exists, redirect to update page, otherwise send blank form try: course = CourseContent.objects.get(cid=c.cid) return HttpResponseRedirect(classUrl+"instructor/syllabus/update/%s" %course.id) except CourseContent.DoesNotExist: form = CourseForm() content = getContent(c, user) content['form'] = form content['message'] = message return render_to_response('instructor/syllabus.html', content, context_instance=RequestContext(request))
def course_update(request, course_id): if request.method == 'POST': c = Course.objects.get(id=course_id) form = CourseForm(request.POST, request.FILES, instance=c) if form.is_valid(): u = request.user c = form.save() dimentions = (150, 150) if len(request.FILES) == 1: image = request.FILES['image'] c.image.save(image.name, createImage(c.image, dimentions)) name = u.first_name + ' ' + u.last_name username = request.user.username variables_for_template = { 'name': name, 'username': username, } return redirect('/course/' + str(course_id) + '/', variables_for_template) else: variables = _course_context(request, course_id) variables['form'] = form variables.update(csrf(request)) return render(request, 'website/course/course_info_edit.html', variables, context_instance=RequestContext(request))
def home(): form = CourseForm() if form.validate_on_submit(): course_name = form.cname.data.upper() course_id = form.cid.data course_sec = form.sec.data.upper() email = form.email.data.lower() reserved = form.reserved.data result = checkCourse(course_name, course_id, course_sec) if result is not None: flash('Unable to find course') else: known = None course = Course.query.filter_by(cname=course_name, cid=course_id, sec=course_sec).first() if course is None: course = Course(cname=course_name, cid=course_id, sec=course_sec) db.session.add(course) db.session.flush() user = User(email=email, course_id=course.id, reserved=reserved) db.session.add(user) else: ckey = course.id result = checkUser(email, ckey, reserved) if result != None: known = True else: user = User(email=email, course_id=ckey, reserved=reserved) db.session.add(user) db.session.commit() return redirect(url_for('complete', known=known)) return render_template('home.html', form=form)
def newCourse(): form = CourseForm(request.form) if request.method == "POST" and form.validate(): name = form.name.data course = Course(name=name) db_session.add(course) db_session.commit() return redirect(url_for('showAllCourses')) return render_template("newcourse.html",form=form)
def create(request): form = CourseForm(data=request.POST or None) try: user = Teacher.objects.get(pk=request.user.id) if form.is_valid(): course = form.create(user) return model_to_dict(course, fields=course_fields) except Exception as e: return e raise Http404
def course_details(id): course = Course.query.get(id) form = CourseForm() #:如果当前登录的教师没有教授这门课程,则禁止访问 if current_user.id != course.teacher.id: abort(403) if form.validate_on_submit(): course.time = form.time.data course.location = form.location.data flash(u'修改信息成功') db.session.commit() return redirect(url_for('course_details', id=id)) return render_template('courseDetails.html', form=form, course=course)
def addCourse(): from forms import CourseForm form = CourseForm(request.form) if request.method == 'POST': if not form.validate(): print(form.errors) c = Course(name=form.name.data, course_type=form.course_type.data, has_practical=form.has_practical.data, desc=form.desc.data, credit=form.credit.data) db.session.add(c) db.session.commit() return render_template('addcourse.html', form=form)
def addcourse(request): if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): new_course = Course(**form.cleaned_data) new_course.save() new_student_course=Student_Course(course_id=form.cleaned_data['course_id'],student_id=request.user.id) new_student_course.save() # redirect, or however you want to get to the main view # return HttpResponseRedirect('/polls/main/') else: form = CourseForm() return render(request, 'polls/addcourse.html', {'form': form})
def addCourse(): ''' Add a new course to the course dashboard. ''' if 'username' not in login_session: return redirect(url_for('welcome')) form = CourseForm() if form.validate_on_submit(): title = form.title.data user_id = login_session['user_id'] description = form.description.data provider = form.provider.data website = form.website.data #If user uploaded an image file, ensure the filename is secure, #then save the file to the filesystem and create a path #to the file in the database. #http://flask.pocoo.org/docs/0.10/patterns/fileuploads/ file = form.image.data if file: filename = secure_filename(file.filename) if file and allowed_file(filename): newCourse = Course(title = request.form['title'], user_id = login_session['user_id'], description = request.form['description'], provider = request.form['provider'], website = request.form['website']) session.add(newCourse) session.commit() #The purpose of this line is to ensure that newCourse.id is #accessable - need it to name the image file on filesystem #http://stackoverflow.com/questions/1316952/sqlalchemy-flush-and-get-inserted-id session.refresh(newCourse) image_destination = 'static/course_images/%s_%s.%s' % (user_id, newCourse.id, get_file_extension(filename)) file.save(dst = image_destination) newCourse.image = image_destination session.commit() else: newCourse = Course(title = request.form['title'], user_id = login_session['user_id'], description = request.form['description'], provider = request.form['provider'], website = request.form['website'], image = None) session.add(newCourse) session.commit() flash('New course %s added!' % newCourse.title) return redirect(url_for('fullCourseList')) else: return render_template('newcourse.html', form = form)
def create_course(): course_form = CourseForm() course_form.semester_id.choices = [(row['id'], row['name']) for row in db.read_all_semesters()] if course_form.validate_on_submit(): rowcount = db.create_course({ 'designation': course_form.designation.data, 'name': course_form.name.data, 'semester_id': course_form.semester_id.data }) if rowcount == 1: flash('Course {} created'.format(course_form.name.data)) return redirect(url_for('all_courses')) return render_template('courses/add.html', form=course_form)
def createcourse(request): if request.method == 'POST': # If the form has been submitted... form = CourseForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... form.save() return HttpResponseRedirect('/createpage/') # Redirect after POST else: form = CourseForm() # An unbound form return render(request, "createpage/createcourse.html", { 'form': form, })
def update(request, id): try: form = CourseForm(request.PUT or None) course = Course.objects.get(author=request.user.id, pk=id) if form.is_valid(): course = form.update(course) content_type = ContentType.objects.get_for_model(course) UserLogEntry.objects.log_action(request.user.id, content_type.pk, course.id, unicode(course.title), 3) return model_to_dict(course, fields=course_fields) else: return form.error_messages except Exception as e: return e raise Http404
def home(): buildings = {} buildings_file = app.config['BUILDINGS_JSON'] with open(buildings_file,'r') as f: buildings = json.load(f) form = CourseForm() delform = PhoneNumberForm() return render_template('home.html', exams=current_user.exams, form=form, delform=delform, buildings=buildings)
def editCourse(course_id): ''' Edit a course on the user's dashboard. ''' if 'username' not in login_session: return redirect(url_for('welcome')) editedCourse = session.query(Course).filter_by(id = course_id).one() if editedCourse.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized to edit this course. Please create your own course in order to edit.');}</script><body onload='myFunction()''>" form = CourseForm() if form.validate_on_submit(): editedCourse.title = form.title.data editedCourse.user_id = login_session['user_id'] editedCourse.description = form.description.data editedCourse.provider = form.provider.data editedCourse.website = form.website.data #http://flask.pocoo.org/docs/0.10/patterns/fileuploads/ file = form.image.data if file and allowed_file(file.filename): filename = secure_filename(file.filename) session.add(editedCourse) session.commit() #The purpose of this line is to ensure that editedCourse.id is #accessable - need it to name the image file on filesystem #http://stackoverflow.com/questions/1316952/sqlalchemy-flush-and-get-inserted-id session.refresh(editedCourse) image_destination = 'static/course_images/%s_%s.%s' % (editedCourse.user_id, editedCourse.id, get_file_extension(filename)) #If there existed a previous image for the course, delete it from filesystem. if editedCourse.image: os.remove(editedCourse.image) file.save(dst = image_destination) editedCourse.image = image_destination session.add(editedCourse) session.commit() session.add(editedCourse) session.commit() flash('Course successfully edited %s' % editedCourse.title) return redirect(url_for('fullCourseList')) else: #Since course description is TextArea input type, need to #prepopulate it with statement below. form.description.data = editedCourse.description return render_template('editcourse.html', course=editedCourse, time = time.time(), form = form)
def add_course(request): context = RequestContext(request) print request.user.groups.filter(name='CourseAdders') if request.user.is_authenticated() == True and request.user.groups.filter( name='CourseAdders').exists(): form = CourseForm(request.GET) return render_to_response('add_course.html', locals(), context) else: return HttpResponseRedirect('/')
def addClasses(request): if request.method == 'POST': courses = request.POST.getlist('course') courseList = [] for course in courses: courseList.append(Course.objects.get(id=course)) print 'courses inputted', courseList form = CourseForm() return render_to_response('schedulizer/addClasses.html', { 'form': form, }, RequestContext(request))
def course_admin_update(request, course_id, prefix): if request.is_ajax(): form = CourseForm(request.POST) if prefix == 'None' else CourseForm(request.POST, prefix=prefix) if form.is_valid(): try: course = Course.objects.get(pk=course_id) course.teacher = form.cleaned_data['teacher'] course.name = form.cleaned_data['name'] course.save() return HttpResponse('OK') except ObjectDoesNotExist: # create new object position = None if Course.objects.count() > 0: course = Course.objects.order_by('-position').all()[0] position = course.position else: position = 1 newcourse = Course() newcourse.teacher = form.cleaned_data['teacher'] newcourse.name = form.cleaned_data['name'] newcourse.position = position newcourse.save() response = {'created_object_id': newcourse.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 edit_course(name): """ Edit a course """ if not current_user.isTeacher: abort(403) add_course = False course = Course.query.filter_by(courseNums=name).first() form = CourseForm(obj=course) if form.validate_on_submit(): course.name = form.name.data course.description = form.description.data db.session.commit() flash(u'课程信息修改成功') return redirect(url_for('admin.list_courses')) form.description.data = course.description form.name.data = course.name course.courseNums = form.courseNums.data return render_template('admin/courses/course.html', action="Edit", add_course=add_course, form=form, course=course, title="Edit Course", code=course.courseNums)
def create(self): form = CourseForm() if request.method == 'POST': instructor_id = form.instructor_id.data instructor_id = ObjectId(instructor_id) if form.validate() == False: return redirect(url_for('new_course')) else: if 'cover_photo' not in request.files: flash('No Cover Photo') return redirect(url_for('new_course')) photo = request.files['cover_photo'] if photo.filename == '': flash('No Photo Selected') return redirect(url_for('new_course')) if photo and self.allowed_file(photo.filename): filename = secure_filename(photo.filename) photo.save(os.path.join(self.uploadFolder, filename)) id = self.newCourse.add(form.title.data, filename, form.description.data, instructor_id) return redirect(url_for('instructor_courses')) return redirect(url_for('instructor_dashboard'))
def add_course(): add_course = True courseNums = ''.join(random.sample(string.ascii_letters+string.digits, 8)) form = CourseForm() if form.validate_on_submit(): course = Course(name=form.name.data, description=form.description.data,teacherName=current_user.name, courseNums=form.courseNums.data) try: # add course to the database db.session.add(course) db.session.commit() flash(u'成功创建一门课程') except: # in case course name already exists flash(u'创建课程失败,可能是选课口令与已存在的课程相同') # redirect to courses page return redirect(url_for('admin.list_courses')) # load course template return render_template('admin/courses/course.html', add_course=add_course, form=form, title="Add Course", code=courseNums)
def enroll(): if not current_user.verified: return redirect(url_for('register',_external=True)) form = CourseForm() if not form.validate_on_submit(): flash("Invalid Course name provided", "warning") return redirect(url_for('home',_external=True)) print(form.data['course']) course = Course.query.filter_by(name=form.data['course']).first() print(course) notif = Exam.query.filter_by(course = course, user= current_user).first() if course and not notif: exam = Exam.make_unique(course,DEFAULT_NOTIF,current_user) db.session.add(exam) db.session.commit() flash("You have successfully registered for this course.", "success") elif not course: flash("Course not found. Please enter the full course code as it appears on ACORN.", "warning") elif notif and course: flash("You are already registered in %s" % course.name, "warning") return redirect(url_for('home',_external=True))
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 dashboard_data(self): data = {} data['logged_in'] = True data['courses'] = [] data['instructor'] = self.newInstructor.get_instructor_by_name( session['instructor']['name']) fields = {"instructor_id": data['instructor']['_id']} courses = self.newCourse.get_courses(fields) data['new_course_form'] = CourseForm() data['new_course_form'].instructor_id.data = data['instructor']['_id'] if courses: for course in courses: course_subscription = self.newStudent_subscription.get_course_subscriptions( course['_id']) course['subscribed'] = course_subscription.count() questions = self.newStudent_question.get_course_questions( str(course['_id'])) course['questions'] = questions.count() data['courses'].append(course) return data
def calendar(): conf = "" #cookies cookies = request.cookies if "courses" in cookies: cs = json.loads(cookies.get("courses")) else: cs = [] if "credits" in cookies: credits = json.loads(cookies.get("credits")) else: credits = 0 for i in cs: credits += data.getCredits(i["crn"]) if "modal" in cookies: m = json.loads(cookies.get("modal")) else: m = "first" modalform = StartForm() form = CourseForm() if form.department.data == None: form.course.choices = data.getDeptCourses('ALL DEPTS') else: form.course.choices = data.getDeptCourses(form.department.data) form_clear = ClearForm() form_remove = RemoveForm() ch = [] #for c in courses: for c in cs: ch.append((c["crn"], (c["title"] + " " + c["sect"]))) form_remove.selcourses.choices = ch error = None #if the form is submitted validly if request.method == 'POST': if form.validate_on_submit(): #reformat the form data into a dictionary of course info course = fmat(form.course.data) #if the course does not conflict with any pre-selected classes, add it to the class schedule conflicts = conflict(course, cs) if len(conflicts) == 0: #courses.append(course) cs.append(course) form_remove.selcourses.choices.append( (course["crn"], (course["title"] + " " + course["sect"]))) credits += data.getCredits(course["crn"]) #if there are one or more conflicts with the current class schedule, do not add it and report conflict else: conlist = ", ".join(conflicts) conf = course["dept"] + " " + course["number"] error = 'The selected class, ' + course["title"] + ' (' + ''.join( course["days"] ) + ', ' + ''.join( course["times"] ) + '),' + ' conflicts with the following courses on your schedule: ' + conlist if form_remove.submit.data: print(form_remove.selcourses.data) for s in form_remove.selcourses.data: print(cs) for i in cs: if i["crn"] == int(s): print("yes") cs.remove(i) form_remove.selcourses.choices.remove( (int(s), (i["title"] + " " + i["sect"]))) credits -= data.getCredits(i["crn"]) if modalform.start.data: if m == "first": m = "yes" else: m = "no" attr = [] for i in cs: attr.extend(data.getAttr(i["crn"])) attr = ", ".join(list(set(attr))) res = make_response( render_template('calendar.html', title='Calendar', modalform=modalform, form=form, cform=form_clear, rform=form_remove, error=error, courses=cs, creds=credits, attributes=attr, conf=conf, m=m)) res.set_cookie("courses", json.dumps(cs)) res.set_cookie("credits", json.dumps(credits)) res.set_cookie("modal", json.dumps(m)) return res