创建基于类的视图允许在django rest框架中的POST后重定向

时间:2018-04-23 13:14:01

标签: python python-2.7 django-rest-framework django-views

我正在尝试创建一个基于类的视图,在HTTP状态201之后,它会重定向到另一个类似/pending_for_approval的网址?我有一个员工休假模式,如果员工申请休假并成功填写表格,他被重定向到另一个网址,说明申请已经完成并待批准,员工也可以查看他的观点结果/她填写了。我该如何实现呢?

到目前为止,我的观点是:

class LeaveApplyAPI(APIView):
    permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]

    """
        {   "applicant":1,
            "approver":1,
            "leave_type":1,
            "leave_subject":"Sick Off",
            "leave_reason":"Sick",
            "start_date":"YY-MM-DD",
            "return_date":"YY-MM-DD"
        }
    """
    # 'slug'-means pecific keyword
    lookup_field = 'pk'
    # permission_classes = (permissions.DjangoObjectPermissions,)
    serializer_class = ApplyLeaveSerializer

    def total_days(self, start_date, return_date):
        oneday = timedelta(days=1)
        # convert str to datetime
        start_date = datetime.strptime(start_date, '%Y-%m-%d')
        return_date = datetime.strptime(return_date, '%Y-%m-%d')
        total_days = 0
        while (start_date <= return_date):
            if not start_date.isoweekday() in (6, 7):
                total_days += 1
            start_date += oneday
        return total_days

    def get(self, request, format=None):
        leaves = Leave.objects.all()
        serializer = ApplyLeaveSerializer(leaves, many=True)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        print(request.data)

        start_date = request.data.get('start_date')
        return_date = request.data.get('return_date')
        total_days = self.total_days(start_date, return_date)

        applicant = Employee.objects.get(id=request.data.pop('applicant'))

        leave_type = LeaveType.objects.get(id=request.data.pop('leave_type'))
        leave_subject = request.data.get('leave_subject')
        leave_reason = request.data.get('leave_reason')
        slug = request.data.get('slug')
        apply_on = request.data.get('apply_on')

        leave = Leave.objects.create(**request.data)
        leave.total_days = total_days
        leave.slug = slug
        leave.apply_on = apply_on
        leave.applicant = applicant
        leave.leave_type = leave_type
        leave.leave_subject = leave_subject
        leave.leave_reason = leave_reason
        leave.save()

        serializer = ApplyLeaveSerializer(leave)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

1 个答案:

答案 0 :(得分:0)

AJAX POST提交中的一个常见模式是在JSON响应中使用带有重定向URL的响应,并允许FE框架执行重定向。

假设您正在使用AJAX,为什么不将redirect_url传递给FE并在FE上执行重定向?

serializer = ApplyLeaveSerializer(leave)
resp = serializer.data
resp['redirect_url'] = 'xyz'
return Response(resp, status=status.HTTP_201_CREATED)

在您的FE中,您可以这样做:

$.ajax({
  ...
})
.done(function(data) {
    redirect_url = data.redirect_url;
    alert('Redirecting!');
    window.location = redirect_url;
}