[Answer]-Forms in Django

1👍

You can still do

f = Student_Form(request.POST)
r = Reagent_Form(request.POST)

and django will assign the appropriate fields.

To hide the FK field,

class Student_Form(ModelForm):
    class Meta:
        model = Student
        exclude = ('reagent', )

class Reagent_Form(ModelForm):
    class Meta:
        model = Reagent

While saving in the view,

def myview(request):
    reagent_form = Reagent_Form(prefix='reagent')
    student_form = Student_Form(prefix='student')
    if request.POST:            
         reagent_form = Reagent_Form(request.POST, prefix='reagent')
         student_form = Student_Form(request.POST, prefix='student')
         if reagent_form.is_valid() and student_form.is_valid():
             reagent = reagent_form.save() #first create the object
             student = student_form.save(commit=False) 
             student.reagent = reagent #then assign to student. 
             student.save()

         #rest of the code. 

Leave a comment