示例#1
0
    def put(self, **kwargs):
        try:
            course = self.item_course_interactor.set_params(
                **kwargs).update_course()
            body = CourseSerializer.serialize(course)
            status = HTTP_STATUS_OK_CODE
        except InvalidEntityException as e:
            body = InvalidEntityExceptionSerializer.serialize(e)
            status = HTTP_BAD_REQUEST_STATUS_CODE

        return body, status
class UserDetailsSerializer(serializers.ModelSerializer):
    skills = SlugRelatedField(many=True,
                              slug_field='name',
                              queryset=Skill.objects.all(),
                              required=False)
    courses_num = serializers.IntegerField(read_only=True)
    skills_num = serializers.IntegerField(read_only=True)
    courses = CourseSerializer(many=True, read_only=True)
    avg_rate = serializers.IntegerField(read_only=True)

    class Meta:
        model = User
        fields = (
            'pk',
            'name',
            'email',
            'phone',
            'gender',
            'address',
            'birth_date',
            'bio',
            'profile_photo',
            'avg_rate',
            'courses_num',
            'skills_num',
            'courses',
            'skills',
        )

    def to_representation(self, instance):
        result = super().to_representation(instance)
        return OrderedDict([(key, result[key]) for key in result
                            if self.ok(result[key])])

    # noinspection PyMethodMayBeStatic
    def ok(self, s):
        if type(s) is list:
            return len(s) > 0
        if s == "":
            return False
        return s is not None
示例#3
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
示例#4
0
    def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
        """List of course.

        Args:
            request: request sent by the client.
            args: Variable length argument list.
            options: Arbitrary keyword arguments.

        Returns:
            Response from the server.
        """
        if request.query_params:
            search = request.query_params
            self.queryset = self.queryset.filter(
                Q(name__contains=search["search"])
                | Q(description__contains=search["search"])
                | Q(place=search["search"])
                | Q(level=search["search"])
                | Q(category=search["search"]))
            serializer = CourseSerializer(self.queryset, many=True)
            return Response(serializer.data, status=200)
        return super().list(request, *args, **kwargs)
示例#5
0
    def update(self,
               request: Request,
               pk: int = None,
               *args: Any,
               **kwargs: Any) -> Response:
        """Update a course.

        Args:
            request: request sent by the client.
            pk: id of the object to be updated.
            args: Variable length argument list.
            options: Arbitrary keyword arguments.

        Returns:
            Response from the server.
        """
        datas = request.data
        course = Course.objects.get(id=pk)
        for attr, value in datas.items():
            if attr == "add_time_table":
                for time_table in value:
                    time_table = time_table.replace("- ", "")
                    time_table_str = re.split(r"\s", time_table)
                    info_time_table = {
                        "day": time_table_str[0],
                        "from_hour": time_table_str[1],
                        "to_hour": time_table_str[2],
                    }
                    new_time_table = TimeTable.objects.create(
                        **info_time_table)
                    course.time_table.add(new_time_table)
            else:
                setattr(course, attr, value)
        course.save()
        serializer = CourseSerializer(course)

        return Response(serializer.data)
示例#6
0
 def post(self, request, *args, **kwargs):
     ser = CourseSerializer(data=request.data)
     if ser.is_valid():
         ser.save()
         return Response('添加成功')
     return Response(ser.errors)
示例#7
0
 def get(self, request, *args, **kwargs):
     queryset = models.Course.objects.all()
     ser = CourseSerializer(instance=queryset, many=True)
     return Response(ser.data)
示例#8
0
def courseApi(request, id=0):
    if request.method == 'GET':
        course = Courses.objects.all()
        course_serializer = CourseSerializer(course, many=True)
        return JsonResponse(course_serializer.data, safe=False)
    elif request.method == 'POST':
        course_data = JSONParser().parse(request)
        course_serializer = CourseSerializer(data=course_data)
        if course_serializer.is_valid():
            course_serializer.save()
            return JsonResponse("Added Successfully!", safe=False)
        return JsonResponse("Failed to add", safe=False)
    elif request.method == 'PUT':
        course_data = JSONParser().parse(request)
        course = Courses.objects.get(CourseId=course_data['CourseId'])
        course_serializer = CourseSerializer(course, data=course_data)
        if course_serializer.is_valid():
            course_serializer.save()
            return JsonResponse("Updated Successfully!", safe=False)
        return JsonResponse("Failed to update", safe=False)
    elif request.method == 'DELETE':
        course = Courses.objects.get(CourseId=id)
        course.delete()
        return JsonResponse("Deleted Successfully!", safe=False)
示例#9
0
 def post(self, request, format=None):
     serializer = CourseSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#10
0
 def get(self, request):
     companies = Course.objects.all()
     serializer = CourseSerializer(companies, many=True)
     return Response(serializer.data)
示例#11
0
 def get(self, request, course_id):
     company = self.get_object(course_id)
     serializer = CourseSerializer(company)
     return Response(serializer.data)
示例#12
0
 def get(self, request, pk, format=None):
     course = Course.objects.get(id=pk)
     serializer = CourseSerializer(course)
     return Response(serializer.data)
示例#13
0
 def get(self, request, format=None):
     courses = Course.objects.filter(students=request.user)
     serializer = CourseSerializer(courses, many=True)
     return Response(serializer.data)