Django: How to make one form from several models containing additional keys

I am trying to create a form on one page that uses several models. Models reference each other. I am having trouble getting the validation form because I cannot figure out how to get the identifier of the two models used in the form into the validation form. I used the hidden key in the template, but I cannot figure out how to make it work in the views

My code is below:

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 , - B , . , ,

+3
1

, , . :

if b_form.is_valid() and c_form.is_valid():
    print "valid"
    b = b_form.save()
    c = c_form.save(commit=False)
    c.b = b
    c.save()
+5

Source: https://habr.com/ru/post/1750548/


All Articles