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

如何在Django FormView中处理跳转/返回URL,实现提交后返回原页面

Django FormView 提交后返回来源页面的标准处理方式

1. 传递来源页面URL(next参数)

从两个来源页面的编辑按钮链接中,直接携带next参数指向当前页面路径:

<!-- 来源页A的编辑链接 -->
<a href="{% url 'item_update' item.pk %}?next={{ request.path }}">编辑</a>

<!-- 来源页B的编辑链接 -->
<a href="{% url 'item_update' item.pk %}?next={{ request.path }}">编辑</a>

2. 表单中携带next参数

在FormView对应的模板里,无需修改表单action(默认提交到当前URL即可),添加隐藏字段传递next参数:

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <!-- 把GET参数里的next值存入隐藏字段 -->
  <input type="hidden" name="next" value="{{ request.GET.next }}">
  <button type="submit">提交</button>
</form>

3. 在FormView中处理跳转逻辑

重写get_success_url方法,优先使用next参数指定的地址,同时通过is_safe_url验证URL安全性(防止恶意跳转),验证不通过则使用默认成功地址:

from django.views.generic.edit import FormView
from django.utils.http import is_safe_url
from django.conf import settings

class ItemUpdateView(FormView):
    form_class = YourItemForm
    template_name = 'item_update.html'
    success_url = '/default/redirect/'  # 默认跳转地址

    def get_success_url(self):
        # 优先取POST中的next(表单提交的隐藏字段),其次取GET中的next
        next_url = self.request.POST.get('next') or self.request.GET.get('next')
        # 验证URL是否属于允许的主机,避免安全风险
        if next_url and is_safe_url(next_url, allowed_hosts=settings.ALLOWED_HOSTS):
            return next_url
        # 没有合法的next参数时,使用默认地址
        return super().get_success_url()

为什么你之前的方法无效?

表单通过POST提交时,action中的?next=xxx属于GET参数,不会自动被包含到POST请求的数据中,因此后端无法直接获取。通过隐藏字段将next参数存入POST数据,或者在后端同时检查GET/POST参数,才能正确拿到来源地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:52:22