gpt4 book ai didi

python - 在 Django 中提交表单后重定向到带参数的主页

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:05 24 4
gpt4 key购买 nike

我正在尝试添加学生的详细信息,这是使用 django 和“POST”方法提交的。提交后,我将详细信息保存在我的“py”文件中。之后我想重定向到主页。之前我用过

return render_to_response("home.html",{ "edit":0,"msg":'saved'}, context_instance=RequestContext(request))

但是在每次刷新主页时它都会向表中插入数据。然后我尝试使用 "HttpResponseRedirect",但它不支持参数传递。我该如何解决这个问题?

添加.py

stud = student(name=request.POST['studname'])
stud.save()
return render_to_response("home.html",{ "edit":0,"msg":'saved'}, context_instance=RequestContext(request))

学生.html

<form id = "addForm" name = "addForm" action = "" method = 'POST' >
<table>
<tr>
<td>Name.</td>
<td><input type="text" name="studname" id="studname"></td>
</tr>
</table>
</form>

最佳答案

你应该看看Post/Redirect/Get .

基本上,

  1. 确保您有一个处理帖子的 POST 方法
  2. 然后将用户重定向到特定页面。
  3. 然后有一个 GET 请求来提供页面。

你可以这样想:

使用 Django 的 redirect

def submitting_student(request):
if request.method == "POST":
stud = student(name=request.POST['studname'])
stud.save()
return redirect("home.html", { "edit":0, "msg":'saved' })

return render_to_response("student.html")

这是关于 PRG pattern 同一主题的另一篇文章

关于python - 在 Django 中提交表单后重定向到带参数的主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26295136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com