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

Django:提交表单后如何跳转至含新增记录pk的指定页面

Django表单提交后直接跳转至带新记录PK的页面解决方案

问题描述

我现有一个含表单的页面,用户可提交数据至数据库;另有一个页面,通过记录的pk值展示该记录的特定字段。请问能否点击提交按钮时,完成数据入库的同时直接跳转至包含该新增记录pk值的目标URL?还是必须分两步操作:先入库,再跳转至带对应pk的URL?

当前表单提交后已成功保存数据并跳转至thanks.html页面,手动输入含pk的URL可正常展示对应记录的字段,相关代码如下:

现有代码

urls.py

from django.urls import path
from django.conf.urls import url, include
from django.views.generic import TemplateView
from .views import *
from . import views

urlpatterns = [
    url(r'^$', UserView.as_view(), name='user_new.html'),
    # form temporarily directs here after saving the data to the DB
    url(r'^thanks/$', TemplateView.as_view(template_name='thanks.html'), name='thanks'),
    # I would like it to go here instead
    path('adherence_agreement/<int:id>', views.adherence_agreement, name='adherence_agreement'),
]

views.py

from django.views.generic.edit import FormView,CreateView
class UserView(CreateView):
    template_name = 'user_new.html'
    form_class = UserForm
    success_url = 'thanks/'

    def post(self, request, *args, **kwargs):
        self.object = None
        if request.method == 'POST':
            form = UserForm(data=request.POST)
            if form.is_valid():
                form.save()
                return self.form_valid(form)
            else:
                return self.form_invalid(form)
        else:
            form = UserForm()

def adherence_agreement(request, id):
    item = get_object_or_404(UserInfo, pk=id)
    return render(request, 'adherence_agreement.html', {'item': item})

adherence_agreement.html

{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container" id="printable">
<br>
<img src="{% static 'RDConnect_300dpi_RGB.jpg' %}" alt="" style=" display: block; margin-left: auto; margin-right: auto; width: 60%; "/>
<br>
<hr>
<h3>Adherence agreement for authorized access to data and biospecimens in the RD-Connect Genome-Phenome Analysis Platform (RDC-GPAP)<sup><a href="#fn1" id="ref1">1</a></sup><small class="text-muted"> to be used together with the <span class="text-info">Code of Conduct</span> for integrated user access to RDC-GPAP for health-related information and human biological samples.</small></h3>
<hr>
<h4>Effective as of 9<sup>th</sup> November 2015</h4>
<p>Communication to Mats G. Hansson, Centre for Research Ethics & Bioethics at Uppsala University: mats.hansson@crb.uu.se</p>
<hr>
<p>I, <span class="text-success">{{ item.first_name }} {{ item.last_name }}</span>, acting on behalf of the <span class="text-success">{{ item.department }}</span>, and holding the position <span class="text-success">{{ item.job_title }}</span>, herewith declare:</p>
<ol type="1">
<li>I have the authority to represent and engage the <span class="text-success">{{ item.department }}</span> for the purpose of the project, <span class="text-success">[project name]</span>. For this project we ask for access to data and/or biospecimens in accordance with our research interests as set out in our completed <span class="text-info">User Verification Form</span> (previous page).</li>
<br>
<li>The <span class="text-success">{{ item.department }}</span> agrees to fully endorse and adhere to the <span class="text-info">Code of Conduct</span> for integrated user access to the RDC-GPAP for health-related information and human biological samples, version 2, 3rd November 2017. It shall apply to all data and biospecimen processing activities carried out within the project <span class="text-success">[project name]</span>. The personal data protection framework is thus in part formalized through this Code.</li>
<br>
<li>The <span class="text-success">{{ item.department }}</span> will ensure the implementation of all measures required by the provisions of this Code.</li>
<br>
<li>The <span class="text-success">{{ item.department }}</span> will ensure compliance with this Code by all staff and personnel working within the project on behalf of the <span class="text-success">

解决方案

完全可以一步完成提交入库+跳转的操作,不需要分两步。核心是利用Django CreateView的特性,重写get_success_url方法来动态生成带新记录PK的目标URL。

修改步骤:

  1. 删除自定义的post方法:CreateView已经内置了表单验证、保存的逻辑,自定义的post方法完全多余,删掉后代码更简洁且不易出错。
  2. 重写get_success_url方法:在UserView中,通过self.object获取刚保存的新记录(CreateView的form_valid方法会自动将保存后的对象赋值给self.object),然后用reverse反向解析目标URL并传入PK参数。

修改后的views.py代码:

from django.views.generic.edit import CreateView
from django.urls import reverse
from django.shortcuts import get_object_or_404, render

class UserView(CreateView):
    template_name = 'user_new.html'
    form_class = UserForm

    def get_success_url(self):
        # 反向解析到adherence_agreement页面,传入新记录的pk作为id参数
        return reverse('adherence_agreement', kwargs={'id': self.object.pk})

def adherence_agreement(request, id):
    item = get_object_or_404(UserInfo, pk=id)
    return render(request, 'adherence_agreement.html', {'item': item})

原理说明:

当表单验证通过后,CreateView会调用form_valid方法保存数据,此时新创建的对象会被赋值给self.object。接着get_success_url方法会被调用,我们在这里利用reverse根据URL名称adherence_agreement生成完整URL,并把新记录的PK作为id参数传入,这样就实现了提交后直接跳转到带PK的目标页面。

这样修改后,用户提交表单后,数据会正常入库,同时自动跳转到/adherence_agreement/[新记录PK]页面,直接展示该记录的字段内容,不需要经过thanks.html中间页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:08:50