def _save_student(cl_data, data): """ Obtiene los datos del formulario, crea un nuevo objeto estudiante y lo salva en la BD. """ #TODO: Las carreras de los estudiantes CI = int(cl_data['ci']) first_name = cl_data['nombre'] last_name = cl_data['pApellido'] + ' ' + cl_data['sApellido'] address = f"{cl_data['calle']} {cl_data['num']} {cl_data['apto']} {cl_data['esc']}" address += f"{cl_data['entre']} {cl_data['y']} {cl_data['repa']} {cl_data['poblado']}" city = cl_data['prov'] email = cl_data['email'] sex = data.sex[int(cl_data['colorSexo']) - 1][1][0] tel = cl_data['tel'] color = int(cl_data['colorRadio']) town = cl_data['mun'] procedence = int(cl_data['procedencia']) ocupation = int(cl_data['ocupacionRadio']) workSec = int(cl_data['sectorRadio']) vinculation = True if int(cl_data['vinculaRadio']) == 1 else False args = locals() args.pop('cl_data') args.pop('data') s = Student(**args) s.save()
def test_log_student_updated_added_event(self): """Check logging signal for newly created dtudent""" # add own root handler to catch student signals output out = StringIO() handler = logging.StreamHandler(out) logging.root.addHandler(handler) # now create student, this should raise new message inside our logger output file student = Student(first_name='Demo', last_name='Student') student.save() # check output file content out.seek(0) self.assertEqual(out.readlines()[-1], 'Student added: Demo Student (ID: %d)\n' % student.id) # now update existing student and check last line in out student.ticket = '12345' student.save() out.seek(0) self.assertEqual(out.readlines()[-1], 'Student updated: Demo Student (ID: %d)\n' % student.id) # remove our handler from root logger logging.root.removeHandler(handler)
def test_log_student_updated_added_event(self): ''' Check logging signal for newly created student ''' # add own root handler to catch student signals output out = StringIO() handler = logging.StreamHandler(out) logging.root.addHandler(handler) # now create student, this should raise new message inside # our logger output file student = Student(first_name='Demo', last_name='Student') student.save() # check output file content out.seek(0) self.assertEqual(out.readlines()[-1], 'Student added: Demo Student (ID: %d)\n' % student.id) # now update existing student and check last line in out student.ticket = '12345' student.save() out.seek(0) self.assertEqual( out.readlines()[-1], 'Student updated: Demo Student (ID: %d)\n' % student.id) # remove our handler from root logger logging.root.removeHandler(handler)
def max_user(max_user_data): """ A student account that fills all fields """ student = Student(**max_user_data) student.set_password(max_user_data['password']) student.is_confirmed = True student.save() return student
def min_user(min_user_data): """ A student account that fulfills minimum requirements """ student = Student(**min_user_data) student.set_password(min_user_data['password']) student.is_confirmed = True student.save() return student
def save(self): """ Save an user like teacher or student""" data = self.cleaned_data data.pop('password_confirmation') is_teacher = data['is_teacher'] data.pop('is_teacher') # Crear el username data['username'] = data['first_name'][:1] + data['last_name'].split( ' ')[0] data['username'] = data['username'].upper() while User.objects.filter(username=data['username']).exists(): data['username'] = data['username'] + str(randrange(1000, 9999)) user = User.objects.create_user(**data) if is_teacher: teacher = Teacher(user=user) teacher.save() else: student = Student(user=user) student.save()
def _add_object_to_db(self, name): if name == 'student': student = Student( first_name=self._random_value('first_name'), last_name=self._random_value('last_name'), ticket=self._random_value(), birthday=timezone.now(), ) student.save() if name == 'group': group = Group( title=self._random_value('title'), notes='note about group', ) group.save() if name == 'user': user = User( username=self._random_value('username'), first_name=self._random_value('first_name'), last_name=self._random_value('last_name'), email=self._random_value("email") + '@example.com', ) # User model have an unique field 'username'. # Generated 'username' can be not unique # in compare with existing objects. # In case of exception repeat creating object 'user'. try: user.save() except: self._add_object_to_db(name)
def register(self, request): # Check for username exists serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): username = serializer.data.get('username') email = serializer.data.get('email') password = serializer.data.get('password') first_name = serializer.data.get('first_name') last_name = serializer.data.get('last_name') else: return Response({'detail': "Invalid Form Data"}, status=400) if username in Student.objects.all().values_list( 'username') or email in User.objects.all().values_list( 'email'): return Response( {'detail': "User with that username already exists"}, status=400) user = Student() user.username = username user.email = email user.set_password(password) user.first_name = first_name user.last_name = last_name user.is_active = False user.save() return Response( { 'detail': "Registered Successfully, please contact Admin for Approval" }, status=201)
def registerConStudent(request): name = request.POST['name'] major = request.POST['major'] age = request.POST['age'] grade = request.POST['grade'] gender = request.POST['gender'] qs = Student(s_name=name, s_major=major, s_age=age, \ s_grade=grade, s_gender=gender) qs.save() return HttpResponseRedirect(reverse('students:listAll'))
def test_create_new_student(self): new_student = Student(name='New Student', dob=datetime.today(), civil_id='1234567890', mobile_number=generate_random_numbers(12), home_number=generate_random_numbers(12), parent_number=generate_random_numbers(12)) new_student.save() self.assertIsInstance(new_student, Student) self.assertTrue(new_student.pk) self.assertEquals('P', new_student.status)
def save(self): student = Student( email = self.validated_data['email'], name = self.validated_data['name'], lastname = self.validated_data['lastname'], carne = self.validated_data['carne'], sship = self.validated_data['sship'] ) password = self.validated_data['password'] student.set_password(password) student.save() return student
def test_log_result_exam_change_students(self): res_exam = Result_exam(valuetion=5) res_exam.save() student = Student(first_name='Ioan', last_name='Serok') student.save() res_exam.students.add(student) res_exam.save() self.out.seek(0) self.assertEqual(self.out.readlines()[-2].strip(), "List of students was modified \ in result_exam {}".format(res_exam.id))
def student_signup(request): email = None if request.user.is_authenticated: email = request.user.email student = Student.objects.filter(email_address=email) # if len(student) > 0: # messages.info(request, 'You have already signed up.') # return redirect('/profile/') if request.method == 'POST': form = EditStudentSignupForm(request.POST) if form.is_valid(): s = Student( email_address=email, first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], student_id=form.cleaned_data['student_id'], college=form.cleaned_data['college'], major=form.cleaned_data['major'], year=form.cleaned_data['year'], resume_link=form.cleaned_data['resume_link'], general_question=form.cleaned_data['general_question'], additional_skills=form.cleaned_data['additional_skills']) skills = s.skills for skill in skills: skills[skill] = form.cleaned_data.get(skill, "") s._skills = skills s.save() return redirect('/profile/') else: logger.error( f"Invalid profile form for student {student}:\n{form}") messages.info( request, 'Your application was invalid and could not be processed. If this error persists, ' 'please contact [email protected].') return redirect('/profile/') else: form = EditStudentSignupForm() return render(request, 'profile/edit_student_profile.html', { 'title': "Student Create profile/", 'form': form })
def handle(self, *args, **options): student_names = [ 'Matthew', 'Aloysius', 'Scott', 'Josh', 'Richard', 'Daniel', 'Tod', 'Joseph', 'Josephine', 'Johan', 'Joe' ] lab_names = [ 'Guess the Number', 'Mad Lab', 'Turtle', 'Contact List', 'Clock', 'Calculator' ] section_names = ['Python', 'HTML+CSS', 'JavaScript', 'Django'] # PURGE DATA StudentLab.objects.all().delete() Student.objects.all().delete() Lab.objects.all().delete() LabSection.objects.all().delete() for student_name in student_names: if User.objects.filter(username=student_name).exists(): User.objects.get(username=student_name).delete() for i, section_name in enumerate(section_names): lab_section = LabSection(name=section_name, index=(i + 1)) lab_section.save() for j in range(3): lab_name = random.choice(lab_names) lab = Lab(name=lab_name, section=lab_section, index=(j + 1)) lab.save() lab_sections = LabSection.objects.all() for student_name in student_names: print('creating ' + student_name) user = User.objects.create_user(student_name, student_name + '@pdxcodeguild.com', 'abc123') group = Group.objects.get(name='students') user.groups.add(group) user.save() student = Student(name=student_name, user=user) student.save() for lab_section in lab_sections: for lab in lab_section.lab_set.all(): if random.randint(1, 10) == 1: continue student_lab = StudentLab( student=student, lab=lab, grade=random.choice([True, True, True, True, False])) student_lab.save()
def student_list(request): if request.method == 'GET': students = Student.objects.all() students = [{'name': s.name, 'id': s.id} for s in students] return JsonResponse(students, safe=False) if request.method == 'POST': name = request.POST.get('name') student = Student(name=name) student.save() context = {'code': 200, 'msg': 'post success!'} return JsonResponse(context)
def create_demo_user(request): me = Student.from_request(request) if not settings.DEMO_MODE: request.session["alerts"].append(("alert-error","Demo users are not enabled at this time.")) return redirect("index") username = "******"%len(Student.objects.all()) user = User.objects.create_user(username, username+"@example.com", str(random.randint(100000000,999999999))) user.save() student = Student(user=user) student.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect("index")
def test_log_monthjournal_delete(self): student = Student(first_name='Kick', last_name='Resl') student.save() monthjournal = MonthJournal(student=student, date=date(2016, 5, 2)) monthjournal.save() # import copy # mj = copy.deepcopy(monthjournal) mj = monthjournal monthjournal.delete() self.out.seek(0) self.assertEqual(self.out.readlines()[-1].strip(), "MonthJournal deleted: %s" % mj)
def regConStudent(request): name = request.POST['name'] major = request.POST['major'] age = request.POST['age'] grade = request.POST['grade'] gender = request.POST['gender'] qs = Student(studentName=name, studentMajor=major, studentAge=age, studentGrade=grade, studentGender=gender) qs.save() return HttpResponseRedirect(reverse('students:stuAll'))
def test_log_monthjournal_add_update(self): student = Student(first_name='Nick', last_name='Rest') student.save() monthjournal = MonthJournal(student=student, date=date(2016, 5, 2)) monthjournal.save() self.out.seek(0) self.assertEqual(self.out.readlines()[-1].strip(), "MonthJournal created: %s" % monthjournal) monthjournal.present_day1 = True monthjournal.save() self.out.seek(0) self.assertEqual(self.out.readlines()[-1].strip(), "MonthJournal updated: %s" % monthjournal)
def test_log_group_add_update_event(self): student = Student(first_name='Demo', last_name='Student') student.save() group = Group(title='TTE') group.save() self.out.seek(0) self.assertEqual(self.out.readlines()[-1], "Group added: %s (ID: %d)\n" % (group.title, group.id)) group.leader = student group.save() self.out.seek(0) self.assertEqual(self.out.readlines()[-1].strip(), "Group edited: {} (ID: {})".format(group.title, group.id))
def register_student_add(request): if request.method=="POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] gender=request.POST['gender'] username=request.POST['username'] password=request.POST['password'] class_id=request.POST['class_id'] # hash the password hashed_password = sha256_crypt.encrypt(password) student=Student(first_name=first_name,last_name=last_name,gender=gender,username=username,password=hashed_password,classid_id=class_id) student.save() return login_student_form(request)
def create(self, validated_data): regnumber = validated_data['regnumber'] email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] password = validated_data['password'] user_obj = Student( regnumber = regnumber, email = email, password = password, first_name = first_name, last_name = last_name, ) user_obj.set_password(password) user_obj.save() return validated_data
def regConStudent(request): name = request.POST['name'] major = request.POST['major'] age = request.POST['age'] grade = request.POST['grade'] gender = request.POST['gender'] # 데이터베이스에 request로부터 전달받은 데이터를 테이블에 저장하는 쿼리 qs = Student(s_name=name, s_major=major, s_age=age, s_grade=grade, s_gender=gender) qs.save() # 마지막으로 웹페이지사용자에게 "학생전체보기 페이지" url인 students/all 에 연결시켜준다. return HttpResponseRedirect(reverse('students:stuAll'))
def test_log_student_deleted_event(self): """Check logging signals for deleted student""" student = Student(first_name='Demo', last_name='Student') student.save() # now override signal # add own root handler to catch student signals output out = StringIO() handler = logging.StreamHandler(out) logging.root.addHandler(handler) # delete existing student and check logger output sid = student.id student.delete() out.seek(0) self.assertEqual(out.readlines()[-1], 'Student deleted: Demo Student (ID: %d)\n' % sid) # remove our handler from root logger logging.root.removeHandler(handler)
def student_add(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): print form.cleaned_data student = Student( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], phone_number=form.cleaned_data['phone_number'], package=form.cleaned_data['package'], # courses=form.cleaned_data['courses'], ??????????????????? ) student.save() return redirect('students_list') else: form = StudentForm() return render(request, 'student_edit.html', {'form': form, 'title': 'Add student'})
def test_link_course(self): course = Course.objects.create( name='Django Base', short_description='Django Base Course') course.save() student = Student( name="Ivan", surname="Ivanov", date_of_birth="1999-09-09", email="*****@*****.**", phone="1234567890", address="Mykolyiv", skype="test") student.save() student.courses.add(course) response = self.client.get('/students/1/') self.assertContains(response, '/courses/{}/'.format(student.id)) self.assertContains(response, 'Django Base')
def stu_details(request): if request.method == 'POST': if request.POST.get('usn') != None and request.POST.get( 'name') != None and request.POST.get( 'sem') != None and request.POST.get('dept') != None: print("Hie") form = Student() form.USN = request.POST['usn'] form.name = request.POST['name'] form.sem = request.POST['sem'] form.Dept = request.POST['dept'] form.save() return redirect('accounts:signup') else: form = Student return render(request, 'accounts/student_details.html')
def insertStudents(request): print("This is the insert Excel page") connection = sqlite3.connect('students.db') cursor = connection.cursor() if request.method == "POST": data = request.POST.copy() student=Student() student.room_no = data.get('room_no') student.block = data.get('block') student.name = data.get('name') student.mob_no = data.get('mob_no') student.id_no = data.get('id_no') print(student.room_no) student.save() #sql_insert_single = "INSERT INTO students(ROOMNO, BLOCK, STUDENT, MOBILE, ID) VALUES('{0}', '{1}', '{2}', '{3}', '{4}')".format(room_no, block, student, mobile, id) #cursor.execute(sql_insert_single) connection.commit() connection.close() return render(request, 'insertStudentExcel.html')
def students(request): if request.method == "POST": sid = request.POST["sid"] firstname = request.POST["firstname"] lastname = request.POST["lastname"] department = request.POST["department"] section = request.POST["section"] year = request.POST["year"] student = Student(student_id=sid, firstname=firstname, lastname=lastname, department=department, section=section, year=year) student.save() return redirect("students") students = Student.objects.all() return render(request, "students.html", {"students": students})
def handle(self, **options): randusersreq = requests.get( "https://randomuser.me/api/?results=100&nat=NL") randusersjson = json.loads(randusersreq.text) randusers = randusersjson['results'] randusernames = map( lambda x: x["name"]["first"].capitalize() + " " + x["name"]["last"] .capitalize(), randusers) for user in randusernames: st = Student(name=user, AK_points=random.randint(0, 20), IT_points=random.randint(0, 20), KU_points=random.randint(0, 20), NL_points=random.randint(0, 20), RE_points=random.randint(0, 20), EN_points=random.randint(0, 20), GE_points=random.randint(0, 20), MA_points=random.randint(0, 20)) st.save()
def test_log_student_deleted_event(self): """Check logging signals for deleted student""" student = Student(first_name='Demo', last_name='Student') student.save() # now override signal # add own root handler to catch student signals output out = StringIO() handler = logging.StreamHandler(out) logging.root.addHandler(handler) # delete existing student and check logger output sid = student.id student.delete() out.seek(0) self.assertEqual(out.readlines()[-1], 'Student Demo Student deleted (ID: %d)\n' % sid) # remove our handler from root logger logging.root.removeHandler(handler)
def post(self, request): data = json.loads(request.body.decode('utf-8')) print(data) # myfile = request.FILES.get('filename') code = data['code'] firstName = data['firstName'] # lastName = request.POST.get('lastName') email = data['email'] # dob = request.POST.get('dob') route = data['route'] address = data['address'] # student = Student(code=code, firstName=firstName, lastName=lastName,email=email, dob=dob, route=route, address=address, image=myfile) student = Student(code=code, firstName=firstName, email=email, route=route, address=address) student.save() return redirect('/students')
def add(request): if request.method == "POST": form = request.POST student = Student() student.name = form['name'] student.registration_number = form['registration_number'] student.address = form['address'] student.age = form['age'] #1 student.school = School.objects.get(pk=form['school']) student.save() return redirect('students:student_detail',student.pk) schools = School.objects.all() context = {'schools': schools} return render(request, 'students/addStudent.html',context)
class StudentTests(TestCase): def setUp(self): self.c = Client() self.u1 = User.objects.create_user("ishara", "*****@*****.**", "ishararulz") self.s1 = Student( user=self.u1 ) self.s1.save() # Give the test users memorable names. self.ishara = self.s1 # Test User Connection decorators. def test_user_fields(self): self.assertEquals(self.s1.username, self.u1.username) self.assertEquals(self.s1.email, self.u1.email) # Test the Profile page. def test_profile_page(self): response = self.c.get("/~ishara") self.assertEqual(response.status_code, 200)
def student_add(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): student = Student() student.name = form.cleaned_data['student_name'] student.surname = form.cleaned_data['student_surname'], student.email = form.cleaned_data['student_email'], student.phone = form.cleaned_data['student_phone'], student.package = form.cleaned_data['student_package'] student.save() return redirect('Student_list') else: form = StudentForm(initial={ 'student_name': '', 'student_surname': '', 'student_email': '', 'student_phone': '', 'student_package': '', }) return render(request,'students/edit.html', {'form': form})
def test_log_student_deleted_event(self): """Check logging signal for deleted student""" # add own root handler to catch student signals output out = StringIO() handler = logging.StreamHandler(out) logging.root.addHandler(handler) # now create and delete student, this should raise new message inside # our logger output file student = Student(first_name='Demo', last_name='Student', ticket='123') student.save() student_id = student.id student.delete() # check output file content out.seek(0) self.assertEqual(out.readlines()[-1], 'Student deleted: Demo Student (ID: %d)\n' % student_id) # remove our handler from root logger logging.root.removeHandler(handler)
def ajax_add_student(request): name = request.POST.get('name') address = request.POST.get('address') phone = request.POST.get('phone') birth = request.POST.get('birth') school = request.POST.get('school') money = request.POST.get('money') created = datetime.datetime.now() updated = datetime.datetime.now() s = Student(name=name, address=address, phone=phone, birth=birth, school=school, money=money, created=created, updated=updated) s.save() # Нужно еще добавить поля return HttpResponse('Создано')
class TestNESViews(TestCase): def setUp(self): self.c = Client() self.u1 = User.objects.create_user("ishara", "*****@*****.**", "ishararulz") self.u1.save() self.s1 = Student(user=self.u1, twitter="isharacomix") self.s1.save() # Give the test users memorable names. self.ishara = self.s1 self.G = Game(title="Foo", code="") self.G.save() self.G.authors.add(self.ishara) # def test_arcade(self): response = self.c.get("/arcade/1/") self.assertEqual(response.status_code, 200) self.assertTrue("http://twitter.com/isharacomix" in response.content) response = self.c.get("/arcade/1/?download", follow=True) self.assertEqual(response.status_code, 200)
def test_Entry_Fields_Links(self): course = Course.objects.create( name='Django Base', short_description='Django Base Course') course.save() student = Student( name="Ivan", surname="Ivanov", date_of_birth="1999-09-09", email="*****@*****.**", phone="1234567890", address="Mykolyiv", skype="test") student.save() student.courses.add(course) response = self.client.get('/students/') self.assertContains(response, 'Django Base') self.assertContains(response, '/students/edit/{}/'.format(student.id)) self.assertContains(response, '/students/remove/{}/'.format(student.id)) self.assertContains(response, '/students/add/') self.assertEqual(student.name, "Ivan") self.assertEqual(student.date_of_birth, "1999-09-09") self.assertEqual(course.name, 'Django Base') self.assertEqual(student.courses.all()[0], course)
class TestMooc(TestCase): def setUp(self): self.c = Client() self.u1 = User.objects.create_user("ishara", "*****@*****.**", "ishararulz") self.u1.save() self.s1 = Student( user=self.u1 ) self.s1.save() p = Page(name="index", content="Hello world") p.save() p = Page(name="test", content="This is a test.") p.save() # Give the test users memorable names. self.ishara = self.s1 # Try to go to the home page. def test_home_page(self): response = self.c.get("/") self.assertEqual(response.status_code, 200) self.assertTrue("/sign-up/" in response.content) # Log in and go to the home page. def test_logged_in_dash(self): self.c.login(username="******", password="******") response = self.c.get("/") self.assertEqual(response.status_code, 200) self.assertTrue("/sign-out/" in response.content) # Make sure searching works. def test_search(self): response = self.c.get("/search/?query=world", follow=True) self.assertTrue( "/help/index/" in response.content )
class TestNESViews(TestCase): def setUp(self): self.c = Client() self.u1 = User.objects.create_user("ishara", "*****@*****.**", "ishararulz") self.u1.save() self.s1 = Student( user=self.u1, twitter="isharacomix" ) self.s1.save() # Give the test users memorable names. self.ishara = self.s1 self.G = Game(title="Foo", code="") self.G.save() self.G.authors.add(self.ishara) # def test_arcade(self): response = self.c.get("/arcade/1/") self.assertEqual(response.status_code, 200) self.assertTrue("http://twitter.com/isharacomix" in response.content) response = self.c.get("/arcade/1/?download", follow=True) self.assertEqual(response.status_code, 200)
def addStudent(request): if request.method == 'GET': return HttpResponse(render(request, 'add_student.html')) elif request.method == 'POST': name = request.POST.get('name') surname = request.POST.get('surname') avg_mark = request.POST.get('avg_mark') group_id = request.POST.get('group_id') if int(avg_mark) > 9: group_id = 2 student = Student() student.name = name student.surname = surname student.avg_mark = avg_mark student.group_id = group_id student.save() return redirect('/groups/all')
class BadgeTests(TestCase): def setUp(self): self.c = Client() # Create the test badge. self.b = Badge( name = "The Super Badge", shortname = "superbadge", description = "This badge is quite super.", graphic = "superbadge" ) self.b.save() # Create some test users. self.u1 = User.objects.create_user("ishara", "*****@*****.**", "ishararulz") self.u2 = User.objects.create_user("alexis", "*****@*****.**", "alexisrulz") self.s1 = Student( user=self.u1 ) self.s2 = Student( user=self.u2 ) self.s1.save() self.s2.save() # Award the badge to s1 self.b.awarded_to.add( self.s2 ) self.b.save() # Give the test users memorable names. self.ishara = self.s1 self.alexis = self.s2 # Test the model's "held_by" method. def test_held_by(self): self.assertFalse( self.b.held_by( self.ishara ) ) self.assertTrue( self.b.held_by( self.alexis ) ) # When an anonymous user visits the badge list (/badges/) they see the # superbadge. def test_view_badge_list(self): response = self.c.get('/badges/') self.assertEqual(response.status_code, 200) response = self.c.get('/badges/superbadge/') self.assertEqual(response.status_code, 200) # When you go to a badge that doesn't exist, you get redirected back to # '/badges'. def test_badge_redirect(self): response = self.c.get('/badges/fakebadge/', follow=True) self.assertEqual(response.redirect_chain, [(u'http://testserver/badges/', 302)]) # When Alexis visits the badge list, she sees a check mark next to # the superbadge. def test_view_badge_list_check(self): self.c.login(username="******", password="******") response = self.c.get('/badges/') self.assertEqual(response.status_code, 200) self.assertTrue( '<i class="icon-ok"></i>' in response.content ) # When Ishara visits the badge list, he doesn't see a check mark next to # the superbadge. def test_view_badge_list_nocheck(self): self.c.login(username="******", password="******") response = self.c.get('/badges/') self.assertEqual(response.status_code, 200) self.assertFalse( '<i class="icon-ok"></i>' in response.content ) # When Alexis visits the badge information, she can add the badge to her # backpack. def test_badge_backpack_button(self): self.c.login(username="******", password="******") response = self.c.get('/badges/superbadge/') self.assertEqual(response.status_code, 200) self.assertTrue( 'http://beta.openbadges.org/issuer.js' in response.content ) # When Ishara visits the badge information, he can not add the badge to his # backpack. def test_view_badge_list_nocheck(self): self.c.login(username="******", password="******") response = self.c.get('/badges/superbadge/') self.assertEqual(response.status_code, 200) self.assertFalse( 'http://beta.openbadges.org/issuer.js' in response.content ) # Check to ensure that you get a 404 for the assertion for Ishara and a # JSON string for Alexis. def test_badge_assertion(self): response = self.c.get('/badges/superbadge/ishara/') self.assertEqual(response.status_code, 404) response = self.c.get('/badges/superbadge/ramen/') self.assertEqual(response.status_code, 404) response = self.c.get('/badges/superbadge/alexis/') self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json')
class LessonTests(TestCase): def setUp(self): self.c = Client() self.t1 = Page( title="index", content="sup" ) self.t2 = Page( title="epic", content=""" = This is a truly epic tale. == OMG === fur reals It stars **Ishara** //Alexis// and __Allen__. --THE END-- """) self.t1.save() self.t2.save() # Let's create a world with three stages. self.W = World( name = "Fun World", shortname = "1", graphic = "foo" ) self.W.save() self.Q = QuizChallenge( shortname = "quiz1", content = "foo" ) self.Q.save() self.l1 = Stage( name = "Fun Level 1", shortname = "1", lesson = self.t2, challenge = self.Q, world = self.W, xlocation = 1, ylocation = 1, graphic = "foo") self.l2 = Stage( name = "Fun Level 2", shortname = "2", lesson = self.t2, world = self.W, xlocation = 1, ylocation = 1, graphic = "foo") self.l3 = Stage( name = "Fun Level 3", shortname = "3", challenge = self.Q, world = self.W, xlocation = 1, ylocation = 1, graphic = "foo", hidden = True) self.l1.save() self.l2.save() self.l3.save() self.l2.prereqs.add(self.l1) self.l3.prereqs.add(self.l1) self.l2.save() self.l3.save() # Create some test users. self.u1 = User.objects.create_user("ishara", "*****@*****.**", "ishararulz") self.u2 = User.objects.create_user("alexis", "*****@*****.**", "alexisrulz") self.s1 = Student( user=self.u1 ) self.s2 = Student( user=self.u2 ) self.s1.save() self.s2.save() # Give the test users memorable names. self.ishara = self.s1 self.alexis = self.s2 self.l1.completed_by.add(self.alexis) self.l1.save() # Anonymous viewers can not access the pages - they will be redirected # to the log-in/sign-up page. def test_anon_lessons(self): pass # When a user visits a stage that doesn't have a lesson, they go directly # to the challenge. def test_go_challenge(self): self.c.login(username="******", password="******") response = self.c.get("/world/1/3/", follow=True) self.assertEqual(response.redirect_chain, [(u'http://testserver/world/1/3/challenge/', 302)]) response = self.c.get("/world/1/3/lesson/", follow=True) self.assertEqual(response.redirect_chain, [(u'http://testserver/world/1/3/challenge/', 302)]) # When a user visits a stage that doesn't have a challenge, they go directly # to the lesson. def test_go_challenge(self): self.c.login(username="******", password="******") response = self.c.get("/world/1/2/", follow=True) self.assertEqual(response.redirect_chain, [(u'http://testserver/world/1/2/lesson/', 302)]) response = self.c.get("/world/1/2/challenge/", follow=True) self.assertEqual(response.redirect_chain, [(u'http://testserver/world/1/2/lesson/', 302)]) # Test the world map. Ishara will see two stages, while Alexis will see 3. def test_world_map(self): self.c.login(username="******", password="******") response = self.c.get("/world/1/") self.assertTrue( "Fun Level 3" in response.content ) self.c.logout() self.c.login(username="******", password="******") response = self.c.get("/world/1/") self.assertFalse( "Fun Level 3" in response.content )
def handle(self, *args, **options): self.stdout.write( u'Function of automatic filling of the Database.' \ u' How many objects need to create? ') # students if 'students' in args: number = int(raw_input( u'Input the number of students: ')) for i in range(number): student = Student( first_name=random.choice(self.first_names), last_name=random.choice(self.last_names), middle_name=random.choice(self.middle_names), ticket=random.choice( self.ticket) + random.choice(self.ticket), student_group=Group.objects.all()[random.randint( 0, Group.objects.count() - 1)], birthday=datetime.today()) student.save() self.stdout.write( u'Objects %s create in database' % student) # groups if 'groups' in args: number = int(raw_input( u'Input the number of groups: ')) for i in range(number): group = Group( title=random.choice(self.title), leader=Student.objects.all()[random.randint( 0, Student.objects.count() - 1)], ) group.save() self.stdout.write( u'Objects %s create in database' % group) # exams if 'exams' in args: number = int(raw_input( u'Input the number of exams: ')) for i in range(number): exam = Exam( science=random.choice(self.science), teacher=random.choice(self.teacher_names), date=datetime.today(), groups=Group.objects.all()[random.randint( 0, Group.objects.count() - 1)]) exam.save() self.stdout.write( u'Objects %s create in database' % exam) # results if 'results' in args: number = int(raw_input( u'Input the number of exam results ')) for i in range(number): result = Result( exams=Exam.objects.all()[random.randint( 0, Exam.objects.count() - 1)], groups=Group.objects.all()[random.randint( 0, Group.objects.count() - 1)], students=Student.objects.all()[random.randint( 0, Student.objects.count() - 1)], result=random.choice(self.results)) result.save() self.stdout.write( u'Objects %s create in database' % result)
def register_view(request): # make sure users that are logged in can't reach this if request.user.is_authenticated and request.user.is_active: return redirect('/') # grab all schools to pass onto registration form schools = School.objects.all() if request.method == 'POST': if request.POST['type'] == 'teacher': try: new_user = User.objects.create_user( username=request.POST['username'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], password=request.POST['password'], email=request.POST['email'] ) except IntegrityError as e: if str(e) == 'column username is not unique': return render(request, 'auth/register.html', { 'schools': schools, 'error': 'Username is already taken.' }) else: return render(request, 'auth/register.html', { 'schools': schools, 'error': 'Registration error. Please try again.' }) needs_tos = Permission.objects.get(codename='needs_tos') new_user.user_permissions.add(needs_tos) new_user.save() teacher_name = new_user.first_name + ' ' + new_user.last_name # grab the selected school model home_school = School.objects.get(pk=request.POST['school']) new_teacher = Teacher(school=home_school) new_teacher.save() z_user = ZerebralUser(user=new_user, teacher=new_teacher) z_user.save() new_user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, new_user) # send the welcome email send_teacher_welcome_email(teacher_name, new_user.email) return redirect('/accounts/tos') elif request.POST['type'] == 'student': try: new_user = User.objects.create_user( username=request.POST['username'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], password=request.POST['password'], email=request.POST['email'] ) except IntegrityError as e: if str(e) == 'column username is not unique': return render(request, 'auth/register.html', { 'schools': schools, 'error': 'Username is already taken.' }) else: return render(request, 'auth/register.html', { 'schools': schools, 'error': 'Registration error. Please try again.' }) needs_tos = Permission.objects.get(codename='needs_tos') new_user.user_permissions.add(needs_tos) new_user.save() student_name = new_user.first_name + ' ' + new_user.last_name # grab the existing parent or create a new one try: new_parent = Parent.objects.get(email__iexact=request.POST['parent_email']) except: new_parent = None try: if new_parent is None: new_parent = Parent( email=request.POST['parent_email'], first_name=request.POST['parent_first_name'], last_name=request.POST['parent_last_name'] ) new_parent.save() new_student = Student( parent_token=generate_token(50), parent=new_parent ) new_student.save() except: new_user.delete() return render(request, 'auth/register.html', { 'schools': schools, 'error': "Please enter your parent's contact info." }) # send email to parent for consent send_consent_email( request.build_absolute_uri('/parent/consent/'+new_student.parent_token), student_name, new_parent.email ) z_user = ZerebralUser(user=new_user, student=new_student) z_user.save() new_user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, new_user) # send the welcome email send_student_welcome_email(student_name, new_user.email) return redirect('/accounts/tos') return render(request, 'auth/register.html', {'schools': schools})
def sign_in(request): me = Student.from_request(request) if "alerts" not in request.session: request.session["alerts"] = [] if me: return redirect("index") if request.method == "POST": if request.POST.get("sign-up") == "sign-up": return redirect("sign-up") elif "username" in request.POST and "password" in request.POST: username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is not None: if Student.objects.filter(user=user).exists(): login(request, user) s = user.student s.last_login = s.this_login s.this_login = timezone.now() if s.last_login is None: s.last_login = s.this_login if s.last_login.day != s.this_login.day: s.modpoints = s.level s.save() return redirect("index") else: request.session["alerts"].append(("alert-error", """This account has not yet been activated. Please check your e-mail for the activation link.""")) return redirect("sign-in") else: request.session["alerts"].append(("alert-error", """Incorrect username or password.""")) return redirect("sign-in") else: return redirect("sign-in") elif "key" in request.GET and "username" in request.GET: key = request.GET["key"] username = request.GET["username"] # Redirect to login if the user account does not exist or has already # been activated. try: user = User.objects.get(username=username) except exceptions.ObjectDoesNotExist: return redirect("sign-in") if Student.objects.filter(user=user).exists(): return redirect("sign-in") # Verify the hash and redirect if it doesn't match. if hashlib.sha256(username+settings.REGISTER_SALT).hexdigest() != key: return redirect("sign-in") # Assuming everything went well... S = Student( user=user ) S.save() user.is_active = True user.save() request.session["alerts"].append(("alert-success", """Verification successful! You may now sign in!.""")) return render(request, "sign-in.html", {'alerts': request.session.pop('alerts', []) }) else: return render(request, "sign-in.html", {'alerts': request.session.pop('alerts', []) })
class StudentModelTests(TestCase): def setUp(self): self.o1 = Ophase.objects.create(name="Testophase 1", is_active=True) self.gc = OphaseCategory.objects.create(name="Super Mario", priority=10) self.assertEqual(self.gc.name, "Super Mario") self.tg = TutorGroup.objects.create( ophase=self.o1, name="Mario", group_category=self.gc) self.assertEqual(self.tg.name, "Mario") self.st = Student(prename="John", name="Doe", email="*****@*****.**", tutor_group=self.tg, want_exam=True) self.n1 = Newsletter(name='Test Newsletter', description='This newsletter is only for test') def test_student_create(self): """Ensure creating of a student object works""" stud1 = Student.objects.create( prename='Cora', name='Nickerson', email='*****@*****.**', tutor_group=self.tg, want_exam=True, ) stud1.save() # check that save works self.assertEqual(stud1.prename, 'Cora') self.assertEqual(stud1.name, 'Nickerson') self.assertEqual(stud1.tutor_group, self.tg) self.assertEqual(stud1.want_exam, True) self.assertEqual(stud1.ophase, self.o1) # test __str__ tg_string = self.tg.__str__() self.assertEqual(stud1.__str__(), 'Nickerson, Cora (%s)' % (tg_string)) # The E-Mail is stored even if the student did not select any # newsletter self.assertEqual(stud1.email, '*****@*****.**') self.assertEqual(stud1.want_newsletter(), False) # Add a newsletter self.n1.save() stud1.newsletters.add(self.n1) self.assertEqual(stud1.want_newsletter(), True) def test_student_update(self): """Ensure update of a student object works""" stud1 = self.st stud1.save() # check values self.assertEqual(stud1.prename, 'John') self.assertEqual(stud1.name, 'Doe') self.assertEqual(stud1.email, '*****@*****.**') self.assertEqual(stud1.tutor_group, self.tg) self.assertEqual(stud1.want_exam, True) self.assertEqual(stud1.ophase, self.o1) stud1.prename = 'John Peter' stud1.save() self.assertEqual(stud1.prename, 'John Peter') self.assertEqual(stud1.name, 'Doe') self.assertEqual(stud1.email, '*****@*****.**') self.assertEqual(stud1.tutor_group, self.tg) self.assertEqual(stud1.want_exam, True) self.assertEqual(stud1.ophase, self.o1) def test_student_foreign_key_ophase(self): """Ensure Student is created with active Ophase as ForeignKey.""" # create Student with an active Ophase self.st.save() self.assertEqual(self.st.ophase.name, "Testophase 1") # create another Ophase which is active (i.e. old Ophase becomes inactive) and update old Person # Ophase ForeignKey should stay the same as before! Ophase.objects.create(name="Testophase 2", is_active=True) self.o1.is_active = False self.o1.save() self.st.email = "*****@*****.**" self.st.save() st = Student.objects.get(pk=self.st.pk) self.assertEqual(st.ophase.name, "Testophase 1") self.assertEqual(st.email, "*****@*****.**") self.assertEqual(Student.objects.count(), 1) # Delete the Ophase object self.o1.delete() # The students object should be deleted too self.assertEqual(Student.objects.count(), 0)
def init(): print 'Existing database will be wiped, continue? (y/n)' choice = raw_input().strip() if choice == 'y': print 'Working...' # Wipe db clean() # Common variable pw = 'sesame' # FYI ACCOUNT_TYPES = { 1: 'teacher', 2: 'student', 3: 'parent', } # Create teachers t = Teacher(first_name='Sesame', last_name='Teacher', email='*****@*****.**', user_type=1) t.save() t.set_password(pw) t.save() # Create classes for i in range(3): index = str(i+1) name = 'Class #' + index code = 'KLS' + index start = end = datetime.now().date() colour = "#" + index*6 k = Klass(teacher=t, name=name, code=code, start=start, end=end, colour=colour) k.save() # Create students students = [ { 'first_name': 'Alton', 'last_name': 'Lau', 'email': '*****@*****.**' }, { 'first_name': 'Marc', 'last_name': 'Lo', 'email': '*****@*****.**' }, { 'first_name': 'Madigan', 'last_name': 'Kim', 'email': '*****@*****.**' } ] classes = Klass.objects.all() for i in range(3): s = students[i] s = Student(first_name=s['first_name'], last_name=s['last_name'], email=s['email'], user_type=2) s.save() s.set_password(pw) s.save() s.klasses = classes[:i+1] k = Klass.objects.all()[0] s = Student.objects.all() # Create notes for i in range(3): index = str(i+1) detail = 'This is note #' + index n = Note(klass=k, detail=detail) n.save() n.students = s[:i+1] print 'All done, goodbye!' else: print 'Fine, I see how it is.'
def handle_oauth(request): me = Student.from_request(request) # Github will give us a code. If we don't get the code or if the secrets # have been screwed up, fail early. if ("code" not in request.GET or request.session.get("secret_state") is None or request.GET.get("state") != request.session.get("secret_state")): request.session["alerts"].append(("alert-error","Error getting token from Github.")) return redirect("index") # Send the data to Github and get our token! keys = (settings.GITHUB_ID, settings.GITHUB_SECRET, request.GET["code"]) try: response = urllib2.urlopen('https://github.com/login/oauth/access_token', 'client_id=%s&client_secret=%s&code=%s'%keys) except: request.session["alerts"].append(("alert-error","Error getting token from Github.")) return redirect("index") data = response.read() if "access_token" not in data: request.session["alerts"].append(("alert-error","Error getting token from Github.")) return redirect("index") # Get the token. token = data[data.find("=")+1:data.find("&")] request.session["access_token"] = token # Now, we find out the user's name and e-mail address. If this user has an # account, we log them in. If not, we create an account for them. try: response = urllib2.urlopen('https://api.github.com/user?access_token=%s'%token) userdata = json.loads(response.read()) username = userdata["login"] try: user = User.objects.get(username=username) except exceptions.ObjectDoesNotExist: user = None response = urllib2.urlopen('https://api.github.com/user/emails?access_token=%s'%token) emaildata = json.loads(response.read()) email = emaildata[0] except: request.session["alerts"].append(("alert-error","Error getting token from Github.")) return redirect("index") # Get the user and username. If the user is in the db, log it in. Otherwise, # create an account. # Log in or create the account. if user and not user.student.banned: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) user.student.unread_since = user.student.last_login user.student.last_login = timezone.now() user.student.save() request.session["alerts"].append(("alert-success","Welcome back, %s!"%username)) return redirect("index") elif user and user.student.banned: request.session["alerts"].append(("alert-error","""This account has been suspended. If you believe this is in error, please contact the site administrator.""")) return redirect("index") elif settings.NO_NEW_ACCOUNTS: request.session["alerts"].append(("alert-error","""New account creation is not enabled at this time. Please try again in the future!""")) return redirect("index") else: user = User.objects.create_user(username, email, str(random.randint(100000000,999999999))) user.save() student = Student(user=user) student.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect("index")