You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django REST Framework中实现更新/删除操作后的重定向

解决方案

要实现更新或删除文章后重定向到/api/路径,你需要重写RetrieveUpdateDestroyAPIView中的update和destroy方法,在完成原有逻辑后返回重定向响应:

修改后的views.py代码如下:

from django.shortcuts import redirect
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from .models import Main
from .serializers import MainSerializer
from rest_framework.permissions import IsAuthenticated

class Update(RetrieveUpdateDestroyAPIView):
    queryset = Main.objects.all()
    serializer_class = MainSerializer
    permission_classes = [IsAuthenticated]

    def update(self, request, *args, **kwargs):
        # 执行父类的更新逻辑
        super().update(request, *args, **kwargs)
        # 重定向到目标路径
        return redirect('/api/')

    def destroy(self, request, *args, **kwargs):
        # 执行父类的删除逻辑
        super().destroy(request, *args, **kwargs)
        # 重定向到目标路径
        return redirect('/api/')

说明

  • RetrieveUpdateDestroyAPIView 默认的update和destroy方法会返回JSON格式的响应,我们通过重写这两个方法,在完成数据更新/删除操作后,返回Django的redirect响应实现页面跳转。
  • 这种方式更适合服务端渲染的场景,如果是前后端分离架构,通常由前端负责处理跳转逻辑。

内容的提问来源于stack exchange,提问作者mohamadhasan zeinali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:07:06