,可以通过以下步骤实现:
以下是一个示例代码:
# forms.py
from django import forms
class Form1(forms.Form):
field1 = forms.CharField()
class Form2(forms.Form):
field2 = forms.EmailField()
# views.py
from django.shortcuts import render
from .forms import Form1, Form2
def handle_forms(request):
form1 = Form1()
form2 = Form2()
if request.method == 'POST':
form1 = Form1(request.POST)
form2 = Form2(request.POST)
if form1.is_valid() and form2.is_valid():
# 处理表单提交逻辑
field1_value = form1.cleaned_data['field1']
field2_value = form2.cleaned_data['field2']
# ...
return render(request, 'template.html', {'form1': form1, 'form2': form2})
# template.html
<form method="post" action="{% url 'handle_forms' %}">
{% csrf_token %}
{{ form1.as_p }}
{{ form2.as_p }}
<input type="submit" value="Submit">
</form>
在上述示例中,我们创建了两个表单类Form1和Form2,然后在视图函数handle_forms中实例化这两个表单类。在模板template.html中,我们使用form1.as_p和form2.as_p来渲染表单字段,并通过循环遍历渲染多个表单。在视图函数中,我们通过判断请求的方法来处理表单提交,如果表单数据有效,则执行相应的逻辑。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云