在Django中,可以使用表单和视图来实现一次提交保存父窗体、子窗体和孙窗体的数据。
下面是一个简单示例代码:
models.py:
from django.db import models
class Parent(models.Model):
name = models.CharField(max_length=100)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Grandchild(models.Model):
child = models.ForeignKey(Child, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
forms.py:
from django import forms
class ParentForm(forms.Form):
name = forms.CharField(max_length=100)
class ChildForm(forms.Form):
parent_id = forms.IntegerField(widget=forms.HiddenInput())
name = forms.CharField(max_length=100)
class GrandchildForm(forms.Form):
child_id = forms.IntegerField(widget=forms.HiddenInput())
name = forms.CharField(max_length=100)
views.py:
from django.shortcuts import render, redirect
from .forms import ParentForm, ChildForm, GrandchildForm
from .models import Parent, Child, Grandchild
def save_data(request):
if request.method == 'POST':
parent_form = ParentForm(request.POST)
child_form = ChildForm(request.POST)
grandchild_form = GrandchildForm(request.POST)
if parent_form.is_valid() and child_form.is_valid() and grandchild_form.is_valid():
# 保存父窗体数据
parent = Parent(name=parent_form.cleaned_data['name'])
parent.save()
# 保存子窗体数据
child = Child(parent=parent, name=child_form.cleaned_data['name'])
child.save()
# 保存孙窗体数据
grandchild = Grandchild(child=child, name=grandchild_form.cleaned_data['name'])
grandchild.save()
return redirect('success')
else:
parent_form = ParentForm()
child_form = ChildForm()
grandchild_form = GrandchildForm()
return render(request, 'form.html', {'parent_form': parent_form, 'child_form': child_form, 'grandchild_form': grandchild_form})
def success(request):
return render(request, 'success.html')
form.html:
<form method="post" action="{% url 'save_data' %}">
{% csrf_token %}
{{ parent_form.as_p }}
{{ child_form.as_p }}
{{ grandchild_form.as_p }}
<input type="submit" value="Submit">
</form>
success.html:
<h1>Data saved successfully!</h1>
在这个示例中,我们定义了三个模型类,分别表示父窗体、子窗体和孙窗体的数据结构。然后,我们创建了三个表单类,用于输入对应的数据。在视图函数中,我们处理了一次提交的逻辑,将用户提交的数据保存到数据库中。最后,我们在前端页面中使用表单类生成了HTML表单,并通过提交按钮将用户输入的数据发送到服务器。
推荐的腾讯云相关产品:腾讯云服务器(https://cloud.tencent.com/product/cvm),腾讯云对象存储(https://cloud.tencent.com/product/cos),腾讯云数据库(https://cloud.tencent.com/product/cdb)。这些产品可以提供云计算领域所需的服务器、存储和数据库等基础设施。
领取专属 10元无门槛券
手把手带您无忧上云