【问题标题】:Django: Refreshing page resubmits formDjango:刷新页面重新提交表单
【发布时间】:2019-03-14 04:22:31
【问题描述】:

我在使用 Django 时遇到了一个奇怪的问题。我可以在数据库中看到我正在提交的视频的两个条目,因为我提交表单的页面在提交后会自动刷新(可以刷新,因为我可以在表格中看到更新的结果)。

但问题是刷新时它会重新提交表单。如果我手动刷新页面,它也会不断提交新视频。在做了一些研究之后,我发现了导致应用程序中 views.py 出现问题的文章。

也有类似的问题,但他们的做法我不确定如何与我的视图集成,因为我也将一些参数返回到页面。 (参考文章:django form resubmitted upon refresh

下面是我已经不太了解的代码。

# Uploading videos form
    if not request.method == "POST":
        f =  UploadForm()   # Send empty form if not a POST method
        args = {"profile_data": profile_data, "video_data": video_data, "form": f}
        return render(request, "home.html", args)

    f = UploadForm(request.POST, request.FILES) # This line is to upload the actual user's content.
    if not f.is_valid():   # Q: Why do we need to check this? And if we do then is the right place and way to do it?
        args = {"profile_data": profile_data, "video_data": video_data}
        return render(request, "home.html", args)

    process_and_upload_video(request)
    args = {"profile_data": profile_data, "video_data": video_data}
    return render(request, "home.html", args)

【问题讨论】:

  • 这就是为什么在有效表单的情况下,您应该使用重定向,而不是呈现响应。
  • 我只是在检查表单是否无效。那么你的意思是我也应该检查“其他”条件吗?我可以在哪里进行重定向?

标签: python html django forms


【解决方案1】:

当您呈现对给定成功 POST 请求的响应时,这是一个已知问题。通常在这里使用Post/Redirect/Get [wiki] 模式:如果 POST 成功,您将重定向到视图,这样浏览器就会发出新的 GET 请求,因此不会在刷新时重新提交,例如:

    # Uploading videos form
    if not request.method == "POST":
        f =  UploadForm()   # Send empty form if not a POST method
        args = {"profile_data": profile_data, "video_data": video_data, "form": f}
        return render(request, "home.html", args)

    f = UploadForm(request.POST, request.FILES) # This line is to upload the actual user's content.
    if not f.is_valid():   # Q: Why do we need to check this? And if we do then is the right place and way to do it?
        args = {"profile_data": profile_data, "video_data": video_data}
        return render(request, "home.html", args)

    process_and_upload_video(request)
    return redirect('some_view')

some_view 通常是一个列表视图,或者是启用提交条目的相同视图。

请注意,您可能应该重构上面的代码:您在这里使用了很多否定逻辑,这使得它相当复杂。

您的代码中还有一些奇怪的模式:例如,您在视图本身中处理视频,这通常不是一个好主意,因为如果这需要很多时候,请求会超时。通常使用 异步任务(例如使用 RabbitMQ)来进行耗时的处理,例如参见 this article

form.is_valid() 通常用于检查是否所有必需的元素都在request.POSTrequest.FILES 中(必需的字段和文件,这些字段是否有效等)。 ModelForm 增加了一些额外的程序员便利,可以将请求转换为模型对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    相关资源
    最近更新 更多