示例#1
0
文件: forms.py 项目: league/l3ms
 def save(self, commit=True):
     e = Enrollment(course=self.course, user=self.user,
                    kind='G' if self.cleaned_data['for_credit'] else 'A')
     self.user.groups.add(self.course.group) # does this save?
     if commit:
         e.save()
     return e
示例#2
0
def enrollment():

    if not session.get('username'):
        return redirect(url_for('login'))

    courseID = request.form.get('courseID')
    courseTitle = request.form.get('title')
    user_id = session.get('user_id')

    if courseID:
        if Enrollment.objects(user_id=user_id, courseID=courseID):
            flash(
                f"Oops! You are already registered in this course {courseTitle}!",
                "danger")
            return redirect(url_for("courses"))
        else:
            Enrollment(user_id=user_id, courseID=courseID).save()
            flash(f"You are enrolled in {courseTitle}!", "success")

    classes = list(
        User.objects.aggregate(*[{
            '$lookup': {
                'from': 'enrollment',
                'localField': 'user_id',
                'foreignField': 'user_id',
                'as': 'r1'
            }
        }, {
            '$unwind': {
                'path': '$r1',
                'includeArrayIndex': 'r1_id',
                'preserveNullAndEmptyArrays': False
            }
        }, {
            '$lookup': {
                'from': 'course',
                'localField': 'r1.courseID',
                'foreignField': 'courseID',
                'as': 'r2'
            }
        }, {
            '$unwind': {
                'path': '$r2',
                'preserveNullAndEmptyArrays': False
            }
        }, {
            '$match': {
                'user_id': user_id
            }
        }, {
            '$sort': {
                'courseID': 1
            }
        }]))

    return render_template("enrollment.html",
                           enrollment=True,
                           title="Enrollment",
                           classes=classes)
    def test_update(self):
        enrollment = Enrollment.create_one(**enrollment_data[0],
                                           course=self.courses[0])
        db.session.commit()
        assert enrollment.status == 'open'

        enrollment.update(status='closed')
        db.session.commit()
        assert Enrollment.get_one(guid=enrollment.guid).status == 'closed'
示例#4
0
def delete():
    course_to_delete = request.form.get('courseID')
    course_Title = request.form.get('courseTitle')
    if course_to_delete:
        Enrollment.objects(courseID=course_to_delete).delete()
        flash(f"You have deleted the course {course_Title}!", "danger")
        return redirect(url_for('enrollment'))
    else:
        flash(f"Oops, you are not enrolled in that class", "danger")
        return redirect(url_for('enrollment'))
    def test_create(self):
        enrollment = Enrollment.create_one(**enrollment_data[0],
                                           guid=self.enrollment_guid,
                                           course=self.courses[0])
        db.session.commit()

        enrollment = Enrollment.get_one(guid=enrollment.guid)
        assert enrollment.status == 'open'
        assert enrollment.start_date == enrollment_data[0]['start_date']
        assert enrollment.end_date == enrollment_data[0]['end_date']
        assert enrollment.course.guid == self.courses[0].guid
        assert enrollment.people == []
示例#6
0
文件: app.py 项目: miku/evreg
def enroll(event_id):
	user = logged_in_user_or_404()
	event = Event.query.get(event_id)
	form = EnrollmentForm()
	form.audit.query = Audit.query.filter(Audit.event==event)
	if form.validate_on_submit():
		enrollment = Enrollment()
		enrollment.user = user
		enrollment.user_id = user.id
		enrollment.audit = form.audit.data
		enrollment.audit_id = enrollment.audit.id
		enrollment.enrollment_date = datetime.datetime.now()
		
		subjects = []
		if form.subject_de.data:
			subjects.append('de')
		if form.subject_en.data:
			subjects.append('en')
		if form.subject_ru.data:
			subjects.append('ru')
		if form.subject_fr.data:
			subjects.append('fr')
		if form.subject_es.data:
			subjects.append('es')

		enrollment.subjects = json.dumps(subjects)
		
		if enrollment.audit.available_seats() <= 1:
			flash(u"Sie können sich für diese Prüfung nicht mehr anmelden, da das Maximum der Teilnehmeranzahl erreicht ist. Bitte wählen Sie einen anderen Termin.")
			enrollment = None
		else:
			db_session.add(enrollment)
			db_session.commit()
		return redirect(url_for('profile'))
	return render_template("enroll.html", **locals())
示例#7
0
文件: tests.py 项目: league/l3ms
def create_sample_courses():
    for y in range(2009,2012):
        create_semester('Fall', y, 9, 1, 12, 31)
        create_semester('Spring', y, 1, 1, 5, 30)
    semesters = Semester.objects.all()

    for co,nm in [("CS 101", "Fundamentals of Computer Science"),
                  ("CS 102", "Programming I"),
                  ("CS 117", "Programming II"),
                  ("CS 150", "Operating Systems"),
                  ("CS 164", "Software Engineering"),
                  ("CS 130", "Algorithms & Data Structures")]:
        for sem in random.sample(semesters, 3):
            tag = co.replace(' ', '').lower() + sem.tag
            grp = Group(name=tag)
            grp.save()
            key = '%x' % random.getrandbits(24)
            c = Course(tag=tag, name=nm, code=co, semester=sem,
                       group=grp, key=key,
                       is_active=_flip())
            c.save()

            us = random.sample(User.objects.all(), random.randrange(4,8))
            num_instructors = random.choice([1,2])
            instrs = us[:num_instructors]
            studs = us[num_instructors:]

            for u in us:
                e = Enrollment(course=c, user=u,
                               kind = 'I' if u in instrs
                               else random.choice(['A', 'G']),
                               notify_on_commit = _flip(),
                               notify_new_grades = _flip())
                e.save()

            ln = CourseLink(course=c, kind='H',
                            url='http://liucs.net/%s/' % tag)
            ln.save()

            if _flip():
                ln = CourseLink(course=c, kind='T',
                                url='http://amazon.com/%s' % nm)
                ln.save()

            if _flip():
                fmt = random.choice(['http://liucs.net/svn/%s/',
                                     'http://github.com/league/%s'])
                ln = CourseLink(course=c, kind='R', url=fmt % tag)
                ln.save()
    def test_relationship__people(self):
        enrollment = Enrollment.create_one(**enrollment_data[0],
                                           course=self.courses[0])
        db.session.commit()

        assert enrollment.people == []

        enrollment.people.append(self.users[0])
        enrollment.people.append(self.users[1])
        db.session.commit()

        assert Enrollment.get_one(guid=enrollment.guid).people == self.users

        enrollment.people.remove(enrollment.people[0])
        db.session.commit()

        assert Enrollment.get_one(guid=enrollment.guid).people == [
            self.users[1]
        ]
def enrollUser(user_id, course_id):
    enroll1 = Enrollment(user_id=user_id,
                         course_id=course_id,
                         term="Spring 2020",
                         grade="IP")
    db.session.add(enroll1)
    try:
        db.session.commit()
        return "Success"
    except Exception as e:
        print(e)
        return "Failed"
def enroll(eventid):
    current_seats = len(
        db.session.query(Enrollment).filter(
            Enrollment.event_id == eventid).all())
    print(get_jwt_identity())
    if current_seats < db.session.query(Event).filter(
            Event.id == eventid).first().seats:
        enroll = Enrollment(event_id=eventid)
        db.session.add(enroll)
        return {"status": "success"}
    else:
        return {"status": "error"}
示例#11
0
def create_mock_enrollment(**kwargs):
    people = kwargs.pop('people', [create_mock_user(), create_mock_user()])
    enrollment = Enrollment.create_one(
        course=create_mock_course(),
        start_date=datetime.utcnow(),
        end_date=datetime.utcnow() + timedelta(days=60),
        status='open',
    )
    for user in people:
        enrollment.people.append(user)

    db.session.commit()
    return enrollment
示例#12
0
def enroll_course(courseID):

    course = Course.query.get_or_404(courseID)

    if not (course in [enrolled.course for enrolled in g.user.enrollments]):

        enroll = Enrollment(user_id=g.user.id, course_id=courseID)

        db.session.add(enroll)
        db.session.commit()

        add_assignments(enroll.id)

        flash(f"Successfully enrolled in { course.title }")

    else:
        flash(f"Failed to enroll in { course.title }")

    return redirect("/")
示例#13
0
def student_dashboard():
    enrollment_obj = Enrollment.query.filter_by(user_id=current_user.user_id).all()
    classes = [Classes.query.get(enroll.get_class_id()) 
               for enroll in enrollment_obj]
    if request.method == 'POST':
        enrollment_code = request.form['enrollment_code']
        # Add a new enrollment to the Enrollment table
        class_id = Classes.query.filter_by(
            enrollment_code=enrollment_code).first().get_id()
        new_enrollment = Enrollment(
            class_id=class_id,
            user_id=current_user.user_id,
            dropped=False
        )
        db.session.add(new_enrollment)
        db.session.commit()
        flash('Registration Successful!', category='success')
        return redirect(url_for('auth.student_class_page', id=class_id))

    return render_template('student_dashboard.html', title='Student Dashboard', classes=classes)
示例#14
0
文件: app.py 项目: ay701/Fun_Projects
def enroll():
    data = api_message()

    if User.query.filter_by(id=data.user_id).first() and \
            Course.query.filter_by(id=data.course_id).first():

        # Add enrollment entry to table
        new_enroll = Enrollment(data.user_id, data.course_id)
        db.session.add(new_enroll)
        db.session.commit()

        data = {
            'message': "Successfully enrolled the course."
        }

        resp = jsonify(data)
        resp.status_code = 201

        return resp
    else:
        return not_found()
示例#15
0
def populatePreviousSemesters(email):
    user = User.query.filter_by(email=email).first()
    courses = db.session.query(Course.id).all()
    print(courses)
    random.shuffle(courses)
    print(courses)
    grades = ["A", "A-", "B+", "B", "B-", "C+", "C", "C-"]
    term = "Spring 2019"
    x = 0
    for course in courses:
        enroll = Enrollment(user_id=user.id,
                            course_id=course[0],
                            term=term,
                            grade=random.choice(grades))
        db.session.add(enroll)
        x += 1
        if x is 4:
            term = "Fall 2019"
        elif x is 8:
            break
    db.session.commit()
示例#16
0
def enrollments_processing(event_id):
    user_id = session.get('user_id', None)
    today = datetime.datetime.today()
    date = today.strftime("%Y-%m-%d-%H:%M")
    if user_id == None:
        return {'error': 'User authorization failed'}, 400
    enrollments = db.session.query(Enrollment)
    event = db.session.query(Event).get(event_id)
    user = db.session.query(Participant).get(user_id)
    enrollment_with_user = enrollments.filter_by(
        event=event, participant=user).one_or_none()
    if request.method == 'POST':
        enrollments = enrollments.filter_by(event=event).all()
        if enrollment_with_user:
            return {"error": "The user is already registered"}, 400
        if len(enrollments) < event.seats:
            new_enrollment_schema = EnrollmentSchema()
            new_enrollment = Enrollment(datetime=date,
                                        event=event,
                                        participant=user)
            db.session.add(new_enrollment)
            db.session.commit()
            try:
                db.session.commit()
            except:
                return jsonify(), 500
            return jsonify(new_enrollment_schema.dump(new_enrollment)), 201, \
              {'Location': f'/enrollments/{new_enrollment.id}'}
        else:
            return {"error": "Not enough seats"}, 400
    elif request.method == 'DELETE':
        if enrollment_with_user:
            db.session.delete(enrollment_with_user)
            try:
                db.session.commit()
            except:
                return jsonify(), 500
            return 204
        else:
            return jsonify(), 204
示例#17
0
 def create_enrollment_with_tuple(tuple):
     return Enrollment(tuple[0], tuple[1])
示例#18
0
def seed_data():
    ron_key = Student(student_id=423491377, first_name ="Ron", last_name = "Weasley").put()
    harry_key = Student (student_id=423491782, first_name ="Harry", last_name = "Potter").put()
    hermione_key = Student(student_id=423491249, first_name="Hermione", last_name="Granger").put()
    malfoy_key = Student(student_id=42391043, first_name="Draco", last_name="Malfoy").put()
    crabbe_key = Student(student_id=42391122, first_name="Vincent", last_name="Crabbe").put()
    goyle_key = Student(student_id=42391063, first_name="Gregory", last_name="Goyle").put()


    ron_wand=Wand(length = 14.0, material = "willow", core="unicorn", owner=ron_key)
    harry_wand=Wand(length = 11.0, material = "holly", core="phoenix feather", owner=harry_key)
    hermione_wand = Wand(length=10.75, material="vinewood", core="dragon heartstring", owner=hermione_key)

    ron_wand.put()
    harry_wand.put()
    hermione_wand.put()

    gryff = House(name="Gryffindor", mascot="Lion", students=[ron_key, harry_key, hermione_key])
    snakes = House(name="Slytherin", mascot="Snake", students=[malfoy_key, crabbe_key, goyle_key])
    hufflepuff = House(name="Hufflepuff", mascot="Badger", students=[])
    ravenclaw = House(name="Ravenclaw",  mascot="Eagle", students=[])

    gryff.put()
    snakes.put()
    hufflepuff.put()
    ravenclaw.put()

    potions = Course(name="Potions", location="dungeon")
    dada = Course(name="Defense Against the Dark Arts", location="3C")
    transfiguration = Course(name="Transfiguration", location="Class 34")
    potions_key = potions.put()
    dada_key = dada.put()
    transfiguration_key = transfiguration.put()

    #dada
    Enrollment(student=ron_key, course=dada_key).put()
    Enrollment(student=harry_key, course=dada_key).put()
    Enrollment(student=hermione_key, course=dada_key).put()

    #potions
    Enrollment(student=hermione_key, course=potions_key).put()
    Enrollment(student=ron_key, course=potions_key).put()
    Enrollment(student=malfoy_key, course=potions_key).put()
    Enrollment(student=crabbe_key, course=potions_key).put()
    Enrollment(student=goyle_key, course=potions_key).put()

    #tranfirguration
    Enrollment(student=harry_key, course=transfiguration_key).put()
    Enrollment(student=hermione_key, course=transfiguration_key).put()
    Enrollment(student=crabbe_key, course=transfiguration_key).put()
    Enrollment(student=goyle_key, course=transfiguration_key).put()

    snape = Teacher(name="Severus Snape", years_experience=5, classes_taught=[potions_key])
    snape.put()
    moody = Teacher(name="Alastor Moody", years_experience=1, classes_taught=[dada_key])
    moody.put()
    mcgonagall = Teacher(name="Minerva McGonagall", years_experience=12, classes_taught=[transfiguration_key])
    mcgonagall.put()
    def test_relationship__course(self):
        enrollment = Enrollment.create_one(**enrollment_data[0],
                                           course=self.courses[1])
        db.session.commit()

        assert enrollment.course == self.courses[1]
示例#20
0
def get(guid):
    return Enrollment.get_one(guid=guid)
    def test_delete(self):
        enrollment = Enrollment.get_one(guid=self.enrollment_guid)
        enrollment.delete()
        db.session.commit()

        assert Enrollment.get_one(guid=enrollment.guid) == None
示例#22
0
 def create(nanodegree_key, status):
     """ Create a new enrollment """
     enrollment = Enrollment(nanodegree_key=nanodegree_key, status=status)
     return enrollment.save()