【问题标题】:Redirect to home page with arguments after submiting form in django在 django 中提交表单后重定向到带有参数的主页
【发布时间】:2014-10-10 08:34:13
【问题描述】:

我正在尝试添加使用 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>

【问题讨论】:

  • 在 django 模型中将名称设为 unigue=true
  • 收到答案后,将其标记为已验证。
  • 但不同学生的姓名、班级等可以相同
  • @user123,同意不同学生的姓名、班级等可以相同。您不必担心做出任何独特的事情,而只需担心重定向行为,如我的回答中所示

标签: python django python-2.7 django-1.4


【解决方案1】:

你应该看看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的同一主题的另一篇文章

【讨论】:

    【解决方案2】:

    尝试在 add.py 中首先检查请求是否是帖子

    例如。

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

    【讨论】:

    • 我检查了“request.method”,但在每次刷新“主页”页面提交后,我得到了 POST 方法。所以它插入数据的时间与我节省的时间一样多
    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多