Exemplo n.º 1
0
 def put(self, request, pk, format=None):
     student = self.get_object(pk)
     serializer = StudentSerializer(student, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 2
0
    def test_gpa_decimals(self):
        matric_no = "1234567"
        data = [{
            "matricNo": matric_no,
            "givenNames": "Philip J",
            "surname": "Fry",
            "academicPlan": "F100-2208",
            "gradYear": "19-20",
            "finalAward3": 1.200
        }]
        serializer = StudentSerializer(data=data, many=True)
        if serializer.is_valid():
            serializer.save()

        student = Student.objects.get(matricNo=matric_no)
        student.save()

        self.assertEqual(str(student.finalAward1), '1.2')
        self.assertEqual(str(student.finalAward2), '1.20')
        self.assertEqual(str(student.finalAward3), '1.200')

        student.finalAward1 = 1.23
        student.save()

        self.decimal_assertion()

        student.finalAward1 = 1.232
        student.save()

        self.decimal_assertion()

        final_award3_dec = str(student.finalAward3).partition('.')[-1]
        self.assertEqual(len(final_award3_dec), 3)
Exemplo n.º 3
0
def createStudent(request):
    # product = Product.objects.get(id=pk)

    serializer = StudentSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)
Exemplo n.º 4
0
def updateStudent(request,pk):
    student = Student_model.objects.get(id=pk)
    serializer = StudentSerializer(instance=student,data=request.data)
    
    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)
Exemplo n.º 5
0
 def post(self, request):
     print(self.request.user)
     serializer = StudentSerializer(data=request.data)
     if serializer.is_valid():
         print(self.request.user)
         serializer.save(user=self.request.user)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response({'status': 'error'})
Exemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = StudentSerializer(data=data, many=True)
        if serializer.is_valid():
            try:
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            except IntegrityError:
                return Response("Data already exists", status=status.HTTP_200_OK)

        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 7
0
 def post(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     pythondata = JSONParser().parse(stream)
     serializer = StudentSerializer(data=pythondata)
     if serializer.is_valid():
         serializer.save()
         res = {"msg": "Data Created"}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type="application/json")
     json_data = JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data, content_type="application/json")
Exemplo n.º 8
0
 def post(self, request):
     serializer = StudentSerializer(data=request.data)
     if serializer.is_valid():
         if request.user.is_student():
             if request.user.student.id == serializer.validated_data['id']:
                 serializer.save()
                 return Response(serializer.data)
             else:
                 return Response(status=status.HTTP_401_UNAUTHORIZED)
         else:
             return Response(status=status.HTTP_404_NOT_FOUND)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
 def put(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     pythondata = JSONParser().parse(stream)
     id = pythondata.get('id')
     stu = Student.objects.get(id=id)
     serializer = StudentSerializer(stu, data=pythondata, partial=True)
     if serializer.is_valid():
         serializer.save()
         res = {"msg": "Partial Data Created"}
         json_data = JSONRenderer().render(res)
         return HttpResponse(json_data, content_type="application/json")
     json_data = JSONRenderer().render(serializer.errors)
     return HttpResponse(json_data, content_type="application/json")
Exemplo n.º 10
0
 def get(self, request, *args, **kwargs):
     json_data = request.body
     stream = io.BytesIO(json_data)
     pythondata = JSONParser().parse(stream)
     id = pythondata.get('id', None)
     if id is not None:
         stu = Student.objects.get(id=id)
         serializer = StudentSerializer(stu)
         json_data = JSONRenderer().render(serializer.data)
         return HttpResponse(json_data, content_type="application/json")
     stu = Student.objects.all()
     serializer = StudentSerializer(stu, many=True)
     json_data = JSONRenderer().render(serializer.data)
     return HttpResponse(json_data, content_type="application/json")
Exemplo n.º 11
0
 def get(self, request, std_id):
     try:
         std = Student.objects.get(pk=std_id)
         serializer = StudentSerializer(std)
         return Response(serializer.data)
     except Student.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
Exemplo n.º 12
0
 def get(self, request, *args, **kwargs):
     matric_no = request.query_params.get("matricNo")
     student_list = request.GET.getlist("years")
     data = self.get_queryset().all()
     if len(student_list) > 0:
         data = data.filter(gradYear__in=student_list)
     if matric_no is None:
         serializer = StudentSerializer(data, many=True)
         return Response(serializer.data, status=status.HTTP_200_OK)
     else:
         try:
             student = data.get(matricNo=matric_no)
             serializer = StudentSerializer(student, many=False)
             return Response(serializer.data, status=status.HTTP_200_OK)
         except ObjectDoesNotExist:
             return Response("Student with MatricNo " + matric_no + " Doesn't Exist", status=status.HTTP_200_OK)
Exemplo n.º 13
0
 def get(self, request):
     lret_dict = dict()
     try:
         lstudents = Student.objects.all()
         lserializer = StudentSerializer(lstudents, many=True)
         lret_dict = dict(students=lserializer.data)
     except Exception, err:
         print(err)
         pass
Exemplo n.º 14
0
    def list(self, request):
        queryset = Student.objects.all()

        serializer = StudentSerializer(queryset, many=True)
        json = JSONRenderer().render(serializer.data)
        print(json)

        print('Reversing')
        stream = io.BytesIO(json)
        data = JSONParser().parse(stream)

        json_list = StudentSerializer(data=data, many=True)
        data.reverse()
        json_list.is_valid()
        json = JSONRenderer().render(json_list.validated_data)
        print(json)

        return Response(json_list.validated_data)
Exemplo n.º 15
0
 def post(self, **kwargs):
     try:
         student = self.create_student_interactor.set_params(
             **kwargs).execute()
         body = StudentSerializer.serialize(student)
         status = HTTP_STATUS_OK_CODE
     except InvalidEntityException as e:
         body = InvalidEntityExceptionSerializer.serialize(e)
         status = HTTP_BAD_REQUEST_STATUS_CODE
     return body, status
Exemplo n.º 16
0
 def test_student_data_stored(self):
     data = [{
         "matricNo": "1234567",
         "givenNames": "Philip J",
         "surname": "Fry",
         "academicPlan": "F100-2208",
         "gradYear": "19-20",
         "finalAward1": 0.0,
         "finalAward2": 0.00,
         "finalAward3": 0.000
     }, {
         "matricNo": "7654321",
         "givenNames": "Hermes",
         "surname": "Conrad",
         "academicPlan": "F100-2208",
         "gradYear": "19-20",
         "finalAward1": 0.0,
         "finalAward2": 0.00,
         "finalAward3": 0.000
     }]
     serializer = StudentSerializer(data=data, many=True)
     if serializer.is_valid():
         serializer.save()
     student1 = Student.objects.filter(
         matricNo="1234567",
         givenNames="Philip J",
         surname="Fry",
         academicPlan="F100-2208",
         gradYear=GraduationYear.objects.get(gradYear="19-20"),
         finalAward1=0.0,
         finalAward2=0.00,
         finalAward3=0.000).exists()
     student2 = Student.objects.filter(
         matricNo="7654321",
         givenNames="Hermes",
         surname="Conrad",
         academicPlan="F100-2208",
         gradYear=GraduationYear.objects.get(gradYear="19-20"),
         finalAward1=0.0,
         finalAward2=0.00,
         finalAward3=0.000).exists()
     self.assertTrue(student1)
     self.assertTrue(student2)
Exemplo n.º 17
0
    def post(self, request, pk):
        teacher = Teacher.objects.get(pk=pk)
        students = []

        for student in request.data['students']:
            students.append(
                teacher.student_set.create(first_name=student['first_name'],
                                           last_name=student['last_name']))

        return Response(StudentSerializer(students, many=True).data)
Exemplo n.º 18
0
 def post(self, request):
     """
     Enroll in a labgroup.
     """
     # ensure all parameters are present in the request data
     for param in ('wwuid', 'labgroup', 'enroll_key'):
         if param not in request.data.keys():
             return Response(status=status.HTTP_400_BAD_REQUEST)
     # load the labgroup from the database
     try:
         labgroup = LabGroup.objects.get(id=request.data['labgroup'])
     except LabGroup.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
     # check enroll key
     if request.data['enroll_key'] != labgroup.enroll_key:
         return Response(status=status.HTTP_403_FORBIDDEN)
     # delete student if it exists
     try:
         student = Student.objects.get(user=request.user)
         student.delete()
     except Student.DoesNotExist:
         pass
     # validate student data in request
     student_data = {
         'user': request.user.id,
         'labgroup': labgroup.id,
         'wwuid': request.data['wwuid'],
     }
     serializer = StudentSerializer(data=student_data)
     if not serializer.is_valid():
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
     # create the student
     student = Student(user=request.user,
                       labgroup=labgroup,
                       wwuid=request.data['wwuid'])
     student.save()
     # add new student to the student group
     group = permissions.get_or_create_student_permissions()
     group.user_set.add(request.user)
     # return successful response
     return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 19
0
 def get(self, request, *args, **kwargs):
     response = super(UserDetailsView, self).get(request, *args, **kwargs)
     if request.user.type_of_user == 'superadmin':
         profile_serializer = SuperAdminSerializer(request.user.superadmin)
     elif request.user.type_of_user == 'staff':
         profile_serializer = StaffSerializer(request.user.staff)
     else:
         profile_serializer = StudentSerializer(
             request.user.student, context={'request': request})
     response.data['profile'] = profile_serializer.data
     response.data['profile']['type'] = request.user.type_of_user
     return response
Exemplo n.º 20
0
    def get(self, request, *args, **kwargs):
        # 获取url中的参数
        # http://127.0.0.1:8000/api/students/aaa/?test=123
        # 取test的值
        print(self.request.GET.get('test', None))

        queryset = self.get_queryset()
        serializer = StudentSerializer(queryset, many=True)
        return Response({
            'data': serializer.data,
            #'sorce': StudentSorceSerializer(StudentSorce.objects.all(), many=True).data
        })
Exemplo n.º 21
0
 def get(self, **kwargs):
     body = []
     try:
         students = self.get_all_students_interactor.set_params(
             **kwargs).execute()
         if students:
             for student in students:
                 body.append(StudentSerializer.serialize(student))
         status = HTTP_STATUS_OK_CODE
     except InvalidEntityException as e:
         body = InvalidEntityExceptionSerializer.serialize(e)
         status = HTTP_BAD_REQUEST_STATUS_CODE
     return body, status
Exemplo n.º 22
0
def student_list(request):
    if request.method == 'GET':
        students = Student.objects.all()
        serializer = StudentSerializer(students, many=True)
        return JsonResponse(serializer.data, safe=False)
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = StudentSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Exemplo n.º 23
0
 def list(self, request, *args, **kwargs):
     keyword = request.GET.get('keyword')
     sex = request.GET.get('sex')
     # if keyword is not None:
     if keyword in ('', None) and sex not in ('', None):
         queryset = Student.objects.filter(sex=sex)
     elif keyword not in ('', None) and sex in ('', None):
         queryset = Student.objects.filter(name__contains=keyword)
     elif keyword not in ('', None) and sex not in ('', None):
         # 执行filter() 方法
         queryset = Student.objects.filter(name__contains=keyword, sex=sex)
     else:
         # 如果参数为空, 执行all()方法
         queryset = Student.objects.all()
     serializer = StudentSerializer(queryset, many=True)
     return Response(serializer.data)
Exemplo n.º 24
0
    def get(self, request, *args, **kwargs):

        stu_id = kwargs.get('pk')

        if stu_id:
            stu_obj = Student.objects.get(pk=stu_id)
            many = False
        else:
            stu_obj = Student.objects.all()
            many = True

        stu_ser = StudentSerializer(stu_obj, many=many)

        return Response({
            'status': 200,
            'messages': '查询成功',
            'result': stu_ser.data
        })
Exemplo n.º 25
0
class TeacherSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(read_only=True)
    students = StudentSerializer(read_only=True, many=True)

    class Meta:
        model = Teacher
        fields = ('id', 'connection_key', 's3_user_key', 'url', 'bio',
                  'street', 'city', 'region', 'country', 'zip_code', 'user',
                  'students')
        depth = 1

    def create(self, validated_data):

        teacher = Teacher.objects.create(**validated_data)
        teacher.generate_key()
        teacher.save()

        return teacher
    def listStudentCurrentAssing(self, request, *args, **kwargs):
        data = request.data
        try:
            with transaction.atomic():
                print("DATA listStudentCurrentAssing:", data)
                _id = data.get("id")

                if _id is not None:
                    assign_student = AssignmentStudent.objects.filter(
                        assignment=_id, activo=True)

                    student_id_list = [
                        element.student_id for element in assign_student
                    ]

                    _students = Student.objects.filter(id__in=student_id_list,
                                                       activo=True)
                    student_serializer = StudentSerializer(_students,
                                                           many=True)

                    return Response({"results": student_serializer.data},
                                    status=status.HTTP_200_OK)

                else:
                    return Response(
                        {
                            "detail":
                            "You didnt send all the necessary data or empty array"
                        },
                        status=status.HTTP_400_BAD_REQUEST)

                return Response(
                    {
                        "detail":
                        "Somenthing was wrong, its not possible to update assignment to student"
                    },
                    status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            return Response({"detail": "User not found"},
                            status=status.HTTP_404_NOT_FOUND)
        except KeyError as e:
            return Response(
                {"detail": "{} is a required field".format(str(e))},
                status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 27
0
    def post(self, request, *args, **kwargs):
        stu_data = request.data

        if not isinstance(stu_data, dict) or stu_data == {}:
            return Response({'status': 500, 'msg': '数据有误'})

        stu_des = StudentDeSerializer(data=stu_data)
        if stu_des.is_valid():
            new_stu = stu_des.save()
            return Response({
                'status': 200,
                'msg': '添加成功',
                'result': StudentSerializer(new_stu).data
            })
        else:
            return Response({
                'status': 500,
                'msg': '添加失败',
                'detail': stu_des.errors
            })
Exemplo n.º 28
0
 def get(self, **kwargs):
     body = {}
     data = []
     try:
         response = self.get_all_courses_interactor.set_params(
             **kwargs).execute()
         if response['courses']:
             body['allPages'] = response['allPages']
             body['offset'] = response['offset']
             for course in response['courses']:
                 try:
                     if course.title:
                         data.append(CourseSerializer.serialize(course))
                 except:
                     data.append(StudentSerializer.serialize(course))
         body['data'] = data
         status = HTTP_STATUS_OK_CODE
     except InvalidEntityException as e:
         body = InvalidEntityExceptionSerializer.serialize(e)
         status = HTTP_BAD_REQUEST_STATUS_CODE
     return body, status
Exemplo n.º 29
0
def student_detail(request, pk):
    try:
        student = Student.objects.get(pk=pk)
    except Student.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = StudentSerializer(student)
        return JsonResponse(serializer.data)

    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = StudentSerializer(student, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

    if request.method == 'DELETE':
        student.delete()
        return HttpResponse(status=204)
Exemplo n.º 30
0
class EnrollStatusSerializer(serializers.Serializer):
    """
    The serializer for enroll status.
    """
    user = UserSerializer(read_only=True)
    student = StudentSerializer(read_only=True)