Reputation: 75
I have two models, a studen and an agent. because student model has some choice field, I'm using ModelForm for Form and that's great. Every Student has an agent:
class Student(models.Model):
ncode = models.CharField(max_length=12)
name = models.CharField(max_length=40)
family = models.CharField(max_length=60)
father = models.CharField(max_length=40)
telephone = models.CharField(max_length=18, blank=True)
address = models.CharField(max_length=256)
reagent = models.ForeignKey(Reagent)
state = models.IntegerField(choices=STUDYING_STATUS)
degree = models.IntegerField(choices=DEGREE_STATUS)
class Reagent(models.Model):
name = models.CharField(max_length=40)
family = models.CharField(max_length=60)
telephone = models.CharField(max_length=18)
These are forms:
class Student_Form(ModelForm):
class Meta:
model = Student
class Reagent_Form(ModelForm):
class Meta:
model = Reagent
But I planed to get both agent and student in one form so, I put them together in one form in template:
<form action="" method="POST"> {% csrf_token %}
<table>
{{ student_form.as_table}}
{{ reagent_form.as_table }}
</table>
<input type="submit" value="Add">
</form>
My problem is how can I get entered informations in separate instances of student and agent forms? if in template was just one forms info I would used f = StudentForm(request.POST)! But the forms are mixed in this case
Upvotes: 0
Views: 67
Reputation: 99680
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.
Upvotes: 1