我正在尝试在一页上制作一个使用多个模型的表单。这些模型相互参考。我在验证表单时遇到问题,因为我不知道如何将表单中使用的两个模型的 id 获取到表单中以进行验证。我在模板中使用了隐藏键,但我不知道如何使其在视图中工作
我的代码如下:
views:
def the_view(request, a_id,):
if request.method == 'POST':
b_form= BForm(request.POST)
c_form =CForm(request.POST)
print "post"
if b_form.is_valid() and c_form.is_valid():
print "valid"
b_form.save()
c_form.save()
return HttpResponseRedirect(reverse('myproj.pro.views.this_page'))
else:
b_form= BForm()
c_form = CForm()
b_ide = B.objects.get(pk=request.b_id)
id_of_a = A.objects.get(pk=a_id)
return render_to_response('myproj/a/c.html',
{'b_form':b_form,
'c_form':c_form,
'id_of_a':id_of_a,
'b_id':b_ide })
models
class A(models.Model):
name = models.CharField(max_length=256, null=True, blank=True)
classe = models.CharField(max_length=256, null=True, blank=True)
def __str__(self):
return self.name
class B(models.Model):
aid = models.ForeignKey(A, null=True, blank=True)
number = models.IntegerField(max_length=1000)
other_number = models.IntegerField(max_length=1000)
class C(models.Model):
bid = models.ForeignKey(B, null=False, blank=False)
field_name = models.CharField(max_length=15)
field_value = models.CharField(max_length=256, null=True, blank=True)
forms
from mappamundi.mappa.models import A, B, C
class BForm(forms.ModelForm):
class Meta:
model = B
exclude = ('aid',)
class CForm(forms.ModelForm):
class Meta:
model = C
exclude = ('bid',)
B 有一个对 A 的外键引用,C 有一个对 B 的外键引用。由于模型是相关的,我希望将它们的表单放在一页上,1 个提交按钮。由于我需要填写 B 和 C 表单的字段,并且我不想从下拉列表中选择 B 的 id,因此我需要以某种方式将 B 表单的 id 获取到表单中,以便验证。我在模板中有一个隐藏字段,我只需要弄清楚如何在视图中执行此操作