django: How to make one form from multiple models containing foreignkeys

Posted by Tim on Stack Overflow See other posts from Stack Overflow or by Tim
Published on 2010-06-17T17:16:24Z Indexed on 2010/06/17 18:13 UTC
Read the original article Hit count: 259

Filed under:
|
|
|
|

I am trying to make a form on one page that uses multiple models. The models reference each other. I am having trouble getting the form to validate because I cant figure out how to get the id of two of the models used in the form into the form to validate it. I used a hidden key in the template but I cant 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 has a foreign key reference to A, C has a foreign key reference to B. Since the models are related, I want to have the forms for them on one page, 1 submit button. Since I need to fill out fields for the forms for B and C & I dont want to select the id of B from a drop down list, I need to somehow get the id of the B form into the form so it will validate. I have a hidden field in the template, I just need to figure how to do it in the views

© Stack Overflow or respective owner

Related posts about django

Related posts about forms