I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it s better to write separate views?
regards
chriss
如何在一个视图中处理两个表单?
原标题:
最佳回答
个人而言,我会使用一个视图来处理每个表单的POST请求。
另一方面,您可以使用隐藏的输入元素来指示使用了哪个表单。
<form action="/blog/" method="POST">
{{ blog_form.as_p }}
<input type="hidden" name="form-type" value"blog-form" /> <!-- set type -->
<input type="submit" value="Submit" />
</form>
...
<form action="/blog/" method="POST">
{{ micro_form.as_p }}
<input type="hidden" name="form-type" value"micro-form" /> <!-- set type -->
<input type="submit" value="Submit" />
</form>
以这样的视角:
def blog(request):
if request.method == POST :
if request.POST[ form-type ] == u"blog-form": # test the form type
form = BlogForm(request.POST)
...
else:
form = MicroForm(request.POST)
...
return render_to_response( blog.html , {
blog_form : BlogForm(),
micro_form : MicroForm(),
})
但是再次强调,我认为每个表单只有一个视图(即使该视图只接受POST请求)比尝试上述方法更简单。
问题回答
就像Ayaz所说的那样,您应该为表单提交按钮命名。
<form action="." method="post">
......
<input type="submit" name="form1">
</form>
<form action="." method="post">
......
<input type="submit" name="form2">
</form>
#view
if "form1" in request.POST:
...
if "form2" in request.POST:
...
如果这两个表格完全不同,将它们由不同的视图处理绝不会有害。否则,你可以使用 zacherates 提到的隐藏输入元素技巧。或者,您可以为每个 submit
元素赋予一个 唯一 的名称,根据那个在视图中区分提交的表格。
相关问题
热门标签
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding