django多form
时间: 2023-10-09 15:17:36 浏览: 92
Django中可以使用多个表单(Multiple Forms)来处理单个视图中的多个表单。这在需要在同一页面上收集多个表单数据的情况下非常有用。
下面是一个简单的例子:
forms.py:
```python
from django import forms
class Form1(forms.Form):
name = forms.CharField()
class Form2(forms.Form):
email = forms.EmailField()
class Form3(forms.Form):
message = forms.CharField(widget=forms.Textarea)
```
views.py:
```python
from django.shortcuts import render
from .forms import Form1, Form2, Form3
def multiple_forms(request):
form1 = Form1()
form2 = Form2()
form3 = Form3()
if request.method == 'POST':
if 'form1_submit' in request.POST:
form1 = Form1(request.POST)
if form1.is_valid():
# 处理表单1的数据
pass
elif 'form2_submit' in request.POST:
form2 = Form2(request.POST)
if form2.is_valid():
# 处理表单2的数据
pass
elif 'form3_submit' in request.POST:
form3 = Form3(request.POST)
if form3.is_valid():
# 处理表单3的数据
pass
context = {
'form1': form1,
'form2': form2,
'form3': form3
}
return render(request, 'multiple_forms.html', context)
```
template:
```html
<form method="POST">
{% csrf_token %}
{{ form1.as_p }}
<button type="submit" name="form1_submit">Submit Form 1</button>
</form>
<form method="POST">
{% csrf_token %}
{{ form2.as_p }}
<button type="submit" name="form2_submit">Submit Form 2</button>
</form>
<form method="POST">
{% csrf_token %}
{{ form3.as_p }}
<button type="submit" name="form3_submit">Submit Form 3</button>
</form>
```
在这个例子中,我们定义了三个表单(Form1、Form2、Form3),并在视图函数中创建了这三个表单的实例。然后,我们在视图函数中处理每个表单的提交,并在模板中显示这三个表单。
在模板中,我们为每个表单创建了一个单独的form元素,并使用不同的提交按钮来提交不同的表单。当表单数据提交时,视图函数会根据提交的表单名称来处理相应的表单数据。
阅读全文