保存或查看表单(使用Django模板系统)

时间:2011-10-27 09:17:33

标签: javascript html django-templates

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

如何在两个不同的地址中提交表单或如何添加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>

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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>