【问题标题】:Form action isn't triggering at all表单操作根本没有触发
【发布时间】:2017-02-09 14:21:53
【问题描述】:

基本上,我目前正在尝试解决这样一个事实,即您必须在表单提交后执行 HttpResponseRedirect 以避免在页面刷新时重复提交。

所以我希望我的表单的提交按钮触发另一个视图,而不是提交当前视图。这是我的html: (我已经把表格拿出来了,因为有很多代码可以水平渲染表格)

<form id= "time-form" method = 'POST' action='' class="dynamic-form" enctype="multipart/form-data">{% csrf_token %}
            <div id="formset-container" class = "formset-container">
                <table>
                <--form is in here-->
                </table>
                <ul>{{ newtime_formset.errors }}</ul>
            </div>
            </br>
            <div>   
                <input type = "submit" id = "save" action="{% url 'tande:create_time' %}" value = "Save Timesheet">
            </div>

所以我希望提交按钮执行 create_time 视图。我们目前处于一个名为时间表的视图中。但它根本没有进入 create_time 视图,它只是停留在当前视图中。

def create_time(request):
    #below isn't printing
    print "create_time view"
    #save the form in here
    return HttpResponseRedirect('timesheet')

两个视图的网址:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^(?P<timesheet_id>[0-9]+)/person/timesheet/$', views.timesheet, name='timesheet' ),
    url(r'^create_time/$', views.create_time, name='create_time' ),  
]

所以我想将时间表保存在 create_time 中,然后返回到时间表以避免重定向....我认为这是有道理的....:S

谢谢

【问题讨论】:

    标签: python html django forms


    【解决方案1】:

    表单中的action参数定义页面提交的位置而不是按钮。

    <form id= "time-form" method = 'POST' action="{% url 'tande:create_time' %}" class="dynamic-form" enctype="multipart/form-data">{% csrf_token %}
         <div id="formset-container" class = "formset-container">
              <table>
                 <--form is in here-->
              </table>
              <ul>{{ newtime_formset.errors }}</ul>
          </div>
          </br>
          <div>   
              <input type = "submit" id = "save" value = "Save Timesheet">
       </div>
    </form>
    

    在您看来,您还需要 django 反向 url 解析器

    def create_time(request):
        #below isn't printing
        print "create_time view"
        #save the form in here
        return HttpResponseRedirect(reverse('timesheet', kwargs={"timesheet_id":<timesheet_id>}))
    

    【讨论】:

    • 还有一个问题,我得到 timesheet_id 全局名称未定义。所以我尝试了kwargs={"timesheet_id": timesheet_object},它是 id 值并获得 NoReverseMatch....尝试了 0 个模式:[]
    • 这是一个约定,您需要将其替换为包含时间表 id 的变量。通常应该是您在表单帖子中创建的对象的 ID
    • 哦,我明白了!上面的“34”是我的时间表ID...我需要在网址中...
    • 啊,我通过输入“tande:timesheet”解决了这个问题。这可能与我在视图前面有一个名为 timesheet 的变量有关...
    猜你喜欢
    • 2013-10-21
    • 2023-03-14
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多