【问题标题】:Save or view a form (using Django template system)保存或查看表单(使用 Django 模板系统)
【发布时间】:2011-12-16 08:49:09
【问题描述】:

我有一个表单,它必须有两种提交方式。如果用户按下“添加”按钮,它将保存在数据库中,如果用户按下“查看”​​按钮,则表单保存在会话中,所以它只是一个视图。这两个过程是同步的,每次按下提交按钮时都会重新加载页面。

如何在两个不同的地址提交表单或者如何添加request.POST变量来指定后端的逻辑?是否可以通过 html、django 模板系统或 javascript?

<table>    
    <form class="add-cv" method="POST" action="{% url add_cv %}">
    {% csrf_token %}
    <!--A lot of form fields-->
    <tr>
        <td>            
            <input type="submit" value="{% trans "Add" %}">
            <input type="submit" value="{% trans "View" %}">
        </td>        
    </tr>
    </form>
</table>

【问题讨论】:

    标签: javascript html django-templates


    【解决方案1】:

    这可以同时使用 javascript 或您的 django 视图函数。

    要将请求发送到您的视图功能广告,然后执行适当的操作,请修改您的 html 表单,如下所示:

    <table>    
    <form class="add-cv" method="POST" action="{% url add_cv %}">
    {% csrf_token %}
    <!--A lot of form fields-->
    <tr>
        <td>            
            <input type="submit" name="submit_Add" value="{% trans "Add" %}">
            <input type="submit" name="submit_View" value="{% trans "View" %}">
        </td>        
    </tr>
    </form>
    </table>
    

    这将确保您可以在 request.POST 字典发送到视图的键中找到“submit_Add”或“submit_Value”,具体取决于单击的提交按钮。您可以像这样在视图中区分这一点:

    def YourView(request):
      if "submit_Add" in request.POST:
           # Actions to add the values in the database.
      elif "submit_View" in request.POST:
           # Actions to save the values in the session.
    

    或者您可以使用 javascript 来区分按钮。(但这将是一种循环方法,只有在您绝对无法重新加载页面时才应使用。) 要使用 javascript 修改您的 html 代码,如下所示:

    <table>    
    <form class="add-cv" method="POST" action="{% url add_cv %}">
    {% csrf_token %}
    <!--A lot of form fields-->
    <tr>
        <td>            
            <input type="button" onclick="func_Add();" value="{% trans "Add" %}">
            <input type="button" onclick="func_View();" value="{% trans "View" %}">
        </td>        
    </tr>
    </form>
    </table>
    

    在模板中定义这两个函数。

    <script type="text/javascript">
      function func_Add(){
         //Required 'Add' actions.
       }
    
      function func_View(){
         //Required 'View' actions.
       }
    </script>
    

    【讨论】:

      【解决方案2】:

      将名称属性添加到提交name="submit1"name="submit2" 然后,您可以在 add_cv 视图中区分它们:

      if "submit1" in request.POST:
          do something
      elif "submit2" in request.POST:
          do something
      

      【讨论】:

      • 哇!真的很干净!谢谢!
      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多